Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 550
Bartosz Bilicki Avatar asked May 25 '16 15:05

Bartosz Bilicki


2 Answers

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.

like image 52
Dennis Winter Avatar answered Oct 19 '22 22:10

Dennis Winter


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
like image 37
helloV Avatar answered Oct 19 '22 22:10

helloV