我是第一次通过 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
我是第一次通过 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
您可以使用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 跳过最后一个任务,因为您没有任何项目要传递给该任务。
我只是维护两个用户列表:“当前”和“以前”。不要删除用户,将其从一个列表移动到另一个列表。
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
如果您想搜索用户帐户,您需要编写脚本、删除系统帐户等。