Ansible 用户模块 - 如何告诉它删除过期的用户帐户?

Ansible User module - how to tell it to remove expired user accounts?

我是第一次通过 Ansible 设置用户管理。我可以使用 Ansible 的用户模块删除过期的帐户吗?我会使用什么条件语句?

请原谅我未经测试的伪代码,但我正在寻找类似以下内容的内容:

tasks:
 - name: remove expired users
   user: name=users.key state=absent force=yes
   when: expired  <----- what condition do I put here?
   with_dict: users

我只维护两个用户列表:"current" 和 "former"。不要删除用户,将其从一个列表移到另一个列表。

tasks:
 - name: ensure users
   user: name=item.key state=present force=yes
   with_dict: current_users

tasks:
 - name: remove expired users
   user: name=item.key state=absent force=yes
   with_dict: former_users

如果您想搜索用户帐户,您需要编写脚本、删除系统帐户等。

您可以使用 shell module to get back the list of users on each host that are expired (as in useradd -e $expire_time) 然后将其传递给用户模块。

例如,我们可以设置一些现在过期的用户:

sudo useradd testexpires -e 2015-09-24
sudo useradd testexpires2 -e 2015-09-22
sudo useradd testexpires3 -e 2015-09-21
sudo useradd testexpires4 -e 2015-09-28
sudo useradd testexpires5 -e 2015-09-21

sudo cat /etc/shadow 然后显示:

...
testexpires:!:16701:0:99999:7::16702:
testexpires2:!:16701:0:99999:7::16700:
testexpires3:!:16701:0:99999:7::16699:
testexpires4:!:16701:0:99999:7::16706:
testexpires5:!:16701:0:99999:7::16699:

然后我们可以检查第 8 列中的纪元日期是否比今天更早,方法是相当可怕地使用这个 shell 一行:

sudo cat /etc/shadow | cut -d: -f1,8 | awk -F: '{if(<{{ epoch_day }} &&  != ""){print [=12=]}}' | cut -d: -f1

我们可以使用内置的 Ansible 轻松获取纪元日期 ansible_date_time variable which gives us the epoch time in seconds and dividing through using Jinja's math filters:

epoch_day  : "{{ ansible_date_time.epoch | int / 86400 | round() }}"

将这些放在一起(并在 awk 中转义引号)给了我们一个剧本,如果你想 运行 它在本地主机上看起来像这样:

- hosts        : localhost
  connection   : local
  gather_facts : yes
  vars  :
    epoch_day  : "{{ ansible_date_time.epoch | int / 86400 | round() }}"
  tasks :    
    - name  : debug epoch day
      debug : var=epoch_day

    - name         : get users expired before today
      shell        : "cat /etc/shadow | cut -d: -f1,8 | awk -F: '{if(<{{ epoch_day }} &&  != \"\"){print [=14=]}}' | cut -d: -f1"
      changed_when : False
      register     : expired_users

    - name  : debug expired_users
      debug : var=expired_users.stdout_lines

    - name : remove expired users
      user :
        name  : "{{ item }}"
        state : absent
        force : yes
      with_items : expired_users.stdout_lines

运行 当您没有任何过期用户时,此剧本将使 Ansible 跳过最后一个任务,因为您没有任何项目要传递给该任务。