您可以使用shell 模块取回每个主机上过期的用户列表(如 中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:
然后,我们可以通过使用这个相当可怕的 shell one liner 检查第 8 列中的纪元日期是否比今天更早:
sudo cat /etc/shadow | cut -d: -f1,8 | awk -F: '{if($2<{{ epoch_day }} && $2 != ""){print $0}}' | cut -d: -f1
我们可以使用 Ansible 的内置ansible_date_time
变量轻松获取纪元日期,该变量为我们提供以秒为单位的纪元时间,并使用Jinja 的数学过滤器进行划分:
epoch_day : "{{ ansible_date_time.epoch | int / 86400 | round() }}"
把它放在一起(并转义 awk 中的引号)给我们一个剧本,如果你想在 localhost 上运行它,它看起来像这样:
- 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($2<{{ epoch_day }} && $2 != \"\"){print $0}}' | 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
当您没有任何过期用户时运行此 playbook 将使 Ansible 跳过最后一个任务,因为您没有任何项目要传递给该任务。