Ansible User Module Password – Generate Password Hash

A common issue when using the Ansible “user” module is setting a password. Although you shouldn’t be writing the password direct into your Ansible YML files, unless this is for testing, or you intend to replace them with something to store them securely and retrieve them at runtime, for example Ansible Vault; you need to be aware that Ansible “user” module expects the password in a certain format.

There’s a number of different ways to get to something suitable, but in this example I’m going to show you mkpasswd. We first need to install it with (assuming you are using Ubuntu/Debian):

sudo apt-get install whois

Then to generate a SHA-512 hash you can use:

mkpasswd --method=sha-512 --salt='thesaltvalue' 'supersecretpassword'

You’ll notice I stuck in a salt too. The salt (assuming its different for each user) ensures that the generated password is also different. Without a salt, if you put in the same plain text password string, you’d end up with the same hash; and that risks easier cracking.

Now we have this string, we can put it into the ansible create user stanza within our Ansible markup, for example:

- name: Create Users
  user:
    name: "{{ item.username }}"
    groups: "{{ item.groups }}"
    generate_ssh_key: yes
    ssh_key_comment: "{{ item.username }}@{{ ansible_fqdn }}"
    password: $6$thesaltvalue$SMif0lqr.9gs/BlCQZWgSO0SAhIDJXmsn6WogfcBMYSyREOImiW/7JH8x62ANjbwYVakxGVL6f7KryPXToOCZ0
  loop: "{{ users }}"

Quick note on the structure of the string. The $6$ at the start specifies the hashing algorithm used, $6$ is SHA-512 (recommended), $5$ is SHA-256 (ok – but use 512 if possible) or $1$ is MD5 (don’t use!).

Leave a comment