The user module can be used to create user accounts and set passwords.
The Problem
How to use the user module to set passwords for Linux accounts? This is something that took me a while to figure out. Luckily, there is a reference to Ansible FAQ in ansible-doc
.
The Solution: Hashing Filters
The answer is taken from Ansible FAQ. To get a sha512 password hash with random salt, we can use the following:
{{ 'password' | password_hash('sha512') }}
Let us store the plaintext password in Ansible vault:
$ ansible-vault view my_vault.yml Vault password: my_password: myPlaintextPassword
Our playbook that uses the vault file my_vault.yml
will look something like this:
--- - name: Create New Users hosts: all become: true gather_facts: false vars_files: - my_vault.yml tasks: - name: Create Users user: name: "{{ item }}" password: "{{ my_password | password_hash('sha512') }}" shell: /bin/bash loop: - alice - vincent
Note that while the playbook does the job, it’s not idempotent. The password hash will be generated every time the playbook is run, and the /etc/shadow
file will be updated.
To make the playbook idempotent, set update_password: on_create
. This will only set the password for newly created users.
--- - name: Create New Users hosts: all become: true gather_facts: false vars_files: - my_vault.yml tasks: - name: Create Users user: name: "{{ item }}" password: "{{ my_password | password_hash('sha512') }}" shell: /bin/bash update_password: on_create loop: - alice - vincent
Thanks for this post !!
This is the most reasonable tutorial for exactly the task. Thank you!
Thanks for this post!!
Much thanks!
Hello, how can i do it for several users?. Same playbook for more users eachone with a different password?.
I’m trying to do it, but i have problem with the variables.
Thankyou for this post. much appreciated!
This may not work depending on the version. You may need to use:
– name: Create user
user:
name: “testuser”
password: “{{ user_vaulted_pass | string | password_hash(‘sha512’) }}”
https://github.com/ansible/ansible/issues/24425
thanks it is working file with ubuntu 18 & centos 7