Ansible for user management -removing dead accounts

Bartosz Bilicki picture Bartosz Bilicki · May 25, 2016 · Viewed 8.5k times · Source

How to efficiently manage user accounts in Ansible? I want to keep user accounts and certificates in list.

When running playbook I would like to create every account from list (thats easy). I also want to remove accounts existing on host, but not present in list.

For now, I figured out list existing accounts awk -F: '($3 >= 1000) {printf "%s\n",$1}' /etc/passwd

and compare it with my list- removing unwanted accounts.

Is there easier way- module that does that out-of-the-box?

Answer

Dennis Winter picture Dennis Winter · Aug 11, 2017

Search for user-id > 1000 when parsing /etc/passwd and add nobody to the list of valid users. This way you're not removing any system users.

vars:
  myusers: ['nobody', 'obama', 'trump', 'clinton', 'you', 'me']

tasks:
- shell: "getent passwd | awk -F: '$3 > 1000 {print $1}'"
  register: users

- user: name={{item}} state=absent remove=yes
  with_items: users.stdout_lines
  when: item not in myusers

Remember to add nobody to your list of valid users.