Manage list of local users via ansible

ansibleusersyaml

I have Linux servers that are using local accounts and I would like to find a way, with ansible, to maintain them.

My goal is to keep the same list of users on all servers and be able to efficiently delete or add a new user on all servers when there is a need for it. I would also like to push the playbook every now and then to correct anything that has been modified on a single server without ansible.

Here is what I got so far:

vars:
 users:
      - login: test1
        group: group1
      - login: test2
        group: group1

tasks:

- name: Maintaining list of users
  user: name={{ item.login }} group={{ item.group }} state=present
  with_items:
      - "{{ users }}"

This playbook works, but I need to add a step that would check if the user already exists and if it does not, then, create it and assign a temporary password.

Is there a way to tell ansible to create a user like in this playbook above, but also tell ansible to give the user a password if the it did not exist?

Thank you.
Thierry.

Best Answer

Assuming you are using Ansible 1.3 or newer, you can specify a password for the user module and add the argument update_password=on_create to get it to only set the password if the user is newly created. If you need the passwords to not be consistent between runs, you can put another task in front of that one to generate a random password, or you might be able to add a task that will generate a per-user random password (although I'm not 100% certain if that is possible).