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?
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With