As far as I know, there are two secure ways (discussable) you could include a password as part of the Ansible user module. Let’s go through it.
Prerequisites
- Ansible
Solutions
Solution 1. Use SHA-512 password with a salt
Step 1. Generate SHA512 password hash with a salt from the CLI.
Step 2. Add the hashed password with a salt value to an Ansible task. For instance:
- name: Add the user 'devcoops' with a specific uid and a primary group of 'sudo'
user:
name: devcoops
comment: DevOps engineer
uid: 1051
group: sudo
password: <password_value_here_generated_from_step_1>
tags:
- users
Note(s). Few things to consider:
- Simpler solution.
- Doesn’t scale well.
Solution 2. Use Ansible Vault
Ansible Vault is an encryption/decryption utility tool used mostly for storing and securing sensitive vars. Now, create a vault file if you haven’t done it already, and add password and password_salt variables.
Step 1. Create a vault file.
ansible-vault create vault
Step 2. You’ll be prompt for vault password. Once done, edit the vault file.
ansible-vault edit vault
Step 2. Once prompt for the vault password, add the secret variables.
password: <some_password_here>
password_salt: <some_password_salt_here>
Step 3. Create a playbook or add the following task below as part of your existing one.
Example playbook:
---
- name: Create new users
hosts: all
become: true
gather_facts: false
vars_files:
- vault
tasks:
- name: Create new users
user:
name: "{{ item }}"
password: "{{ password | password_hash('sha512', password_salt) }}"
shell: /bin/bash
update_password: on_create
loop:
- devcoops
- bob
- alice
tags:
- users
Note(s). A couple of things to consider:
- The password_salt var will prevent the task getting “changed” every time it runs.
- New users will share the same password and password_salt initially. Not a big deal though as long as the users login in a short period of time, hence getting prompt to update their password.
- This isn’t a granular approach, if you want to set parameters like uid, group, comment.
- Although encrypted, the Ansible vault file will be part of VCS, so you might consider migrating to a more well-rounded secret management solution, HashiCorp Vault for instance.
Conclusion
If you can think of any other alternative solution, please do let me know in the comment section below. On a side note, follow our official channel on Telegram.