RH294 Ch 5: Keeping Secrets with Ansible Vault
Passwords and keys do not belong in plain text in a Git repository. Ansible Vault encrypts whole files with AES256; playbooks use them like any other vars file, and Ansible decrypts them in memory at run time.
The commands - ansible-vault create secret.yml: opens an editor and saves the file encrypted. - ansible-vault encrypt api.yml: encrypts an existing file in place. - ansible-vault view secret.yml / edit / decrypt. - ansible-vault rekey secret.yml: changes the password; it asks for the old and the new one.
An encrypted file starts with $ANSIBLEVAULT;1.1;AES256.
Password files. Typing the password every time is slow and impossible in automation. Store it in a file only you can read and point Ansible at it:
bash echo 'webasha123' vault-pass chmod 600 vault-pass
Then either pass --vault-password-file vault-pass (or --ask-vault-pass to be prompted) or set it once in ansible.cfg:
ini [defaults] vaultpasswordfile = ./vault-pass
For rekey without prompts: ansible-vault rekey --vault-password-file old --new-vault-password-file vault-pass file.yml. Never commit the password file itself.
Using a vaulted file
yaml - name: Developer account hosts: dev varsfiles: - secret.yml tasks: - ansible.builtin.user: name: devuser password: "{{ devpass | passwordhash('sha512') }}"
The user module expects the password already hashed, as it would appear in /etc/shadow. The passwordhash('sha512') filter produces a $6$ hash. Passing the plain password stores it unhashed and nobody can log in.
With ansible-navigator, the password file is read on the control node and handed to the execution environment, so the same ansible.cfg setting works for ansible-navigator run.
Common mistakes - Forgetting passwordhash, or writing passwordhash(sha512) without quotes. - A password file with the wrong permissions or a trailing space in the password. - Encrypting a file with one password and running with another: the error is "Decryption failed". - Leaving a decrypted copy lying around after ansible-vault decrypt; prefer view and edit.