Search code examples
ansibleuser-management

Ansible for user management -removing dead accounts


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?


Solution

  • 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