Encrypt sensitive passwords in Ansible playbook

Keeping passwords in Ansible playbooks can be a bad idea, and as such these passwords should be encrypted.

Passwords can be encrypted by using the ansible-vault command with the parameter encrypt_string. See the example below:

ansible-vault encrypt_string 'password_to_be_encrypted' --name 'any_ansible_key_name' | tee -a group_vars/path/to/file.yml

You will then be prompted for a vault password. Inside your group_vars/path/to/file.yml you’ll now notice your variable any_ansible_key_name with an encrypted value.

When running your playbook, you simply add the –ask-vault-pass flag to prompt for your vault password. Should you not include your flag, no variable data will be unencrypted, and you’re playbook run will fail. See example below:

ansible-playbook --ask-vault-pass main.yml

Enter your vault password when prompted.