6

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?

Bartosz Bilicki
  • 12,599
  • 13
  • 71
  • 113
  • I have one thought: use your snippet in a local fact (http://docs.ansible.com/ansible/playbooks_variables.html#local-facts-facts-d) so that the users on each server can be accessed as an array from the playbook. – Matthew Schuchard May 25 '16 at 16:07

3 Answers3

8

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.

Dennis Winter
  • 2,027
  • 4
  • 32
  • 45
4

WARNING CAUTION Do it only if you are absolutely sure about the user to be removed. This may make your system useless if you remove system users like root.

Few lines of Ansible can do what you are asking for. Leverage the user module.

  vars:
    myusers: ['root', 'bin', 'mail', 'obama', 'trump', 'clinton', 'you', 'me']

  tasks:
  - shell: 'cut -d: -f1 /etc/passwd'
    register: users
  - user: name={{item}} state=absent remove=yes
    with_items: users.stdout_lines
    when: item not in myusers
helloV
  • 50,176
  • 7
  • 137
  • 145
  • 2
    You need to be really careful about doing things this way. You would need to specify all of the system users or it will remove them. – MillerGeek May 25 '16 at 19:31
  • @smiller171 you are correct. If not used correctly, it will render the machine useless. – helloV May 25 '16 at 20:51
  • The solution I use has you specify users to remove, rather than deleting everything not in a list. – MillerGeek May 25 '16 at 20:53
  • Also just suggested an edit so that your example doesn't mark anything as changed unless it has changed something. – MillerGeek May 25 '16 at 20:54
  • With more recent versions of Ansible you'd use `loop`. Having said that, this code will fail with `'dict object' has no attribute 'stdout_lines' if no items exist (e.g. if you try extending this code to groups). – Snowcrash Jan 07 '20 at 08:58
0

Try using this Ansible role I wrote: https://galaxy.ansible.com/smiller171/manage_users

MillerGeek
  • 3,057
  • 20
  • 23