Ansible Vault
Ansible vault has been a great tool for keeping passwords and other sensitive data safe. Without sacrificing usability.
It stores your passwords as values in variables. All in a password protected and encrypted file. After which, you can use the variables in your ansible scripts.
You can use the ansible-vault command to manage your vault.
Managing Encrypted Files
ansible-vault create secret.yaml
Creates an encrypted vault named secret.yaml. When ran, you well be prompted to set a password for the vault. Then, a blank file will be opened in your default editor. (Vim anyone?)
You can also store your vault password in a separate file. If you go this route, you’ll want to make sure the file is in a secure location such as /root with limited permissions.
For example, here’s how you would create a vault and use a file called vault-pass as the vault password file:
ansible-vault create --vault-password-file=vault-pass secret.yaml
For the above, the file vault-pass must exist and have a single line with the password you want to use for the vault.
Commonly used ansible-vault commands:
create
- Creates new encrypted file
encrypt - Encrypts an existing file
encrypt_string - Encrypts a string
decrypt - Decrypts an existing file
rekey - Changes password on an existing file
view - Shows contents of an existing file
edit - Edits an existing encrypted file
Using Vault in Playbooks
You can set your default vault password file under defaults in ansible.cfg like so:
If you don’t have it set, you can also choose to have ansible prompt you whenever it attempts to access your vault with the option:
--vault-id @prompt
This also enables a playbook to work with multiple Vault-encrypted files with different passwords set.
ansible-playbook --ask-vault-pass Can be used if you all your Vaults have the same password. And you want to be prompted for the password once.
ansible-playbook --vault-password-file=secret can also be used at the command line to obtain the password from a file.
Here’s an example where we use an api token in a task, but we want to keep that a secret. The Vault variable here is set as my_api_token:
Managing Files with Sensitive Variables
Make sure to keep your encrypted and unencrypted variables separate. You can include your Vault in host or group variables or call it in a playbook using the vars_files parameter.
Vault options for ansible-playbook command
Use --help and grep to quickly see vault options:
Vault options for ansible.cfg
Use the same strategy to quickly see vault options to set globally in ansible.cfg: