Sensitive Data -- Ansible Vault¶
Passwords and secrets should not be in plain text. Ansible Vault encrypts them.
# Create a vault password file (so you don't type it every time)
nano ~/ansible/.vault_pass
# Type a password, save
chmod 600 ~/ansible/.vault_pass
Using an editor rather than echo "password" > .vault_pass keeps the password out of your shell history.
Add to ansible.cfg under [defaults]:
Create encrypted variables:
Put your secrets in there:
---
vault_nas_samba_password: "your-samba-password"
vault_borg_passphrase: "generate-a-long-random-string"
vault_vaultwarden_admin_token: "generate-a-long-random-string"
vault_cloudflared_token: "your-cloudflare-tunnel-token"
vault_forgejo_secret_key: "generate-a-long-random-string"
vault_paperless_db_password: "generate-a-long-random-string"
Reference vault variables in other files with:
A vault file named vault.yml doesn't match any inventory group, so Ansible won't auto-load it from group_vars/. Load it explicitly in the playbook:
(The worked example's playbooks/base.yml does exactly this.)
Commands (run from ~/ansible/):
# Create an encrypted file (opens your $EDITOR, encrypts on save)
ansible-vault create inventory/group_vars/vault.yml
# Edit the vault file (decrypts, opens your $EDITOR, re-encrypts)
ansible-vault edit inventory/group_vars/vault.yml
# View without editing (decrypts to stdout)
ansible-vault view inventory/group_vars/vault.yml
# Re-encrypt with a new password
ansible-vault rekey inventory/group_vars/vault.yml
To add a new secret, ansible-vault edit the file, add a new vault_-prefixed key, and reference it in your roles or templates as {{ vault_some_new_secret }}.
Encrypting a single value¶
You don't have to encrypt a whole file โ you can drop one encrypted string into an otherwise-plaintext vars file. Useful for a single secret alongside normal config.
It prints a block you paste straight into a YAML file:
Ansible decrypts it automatically at runtime, just like a fully-encrypted file.
If you don't use a password file¶
Without vault_password_file in ansible.cfg, pass the
password at runtime:
Best practices¶
Keep the key out of git
The whole point is defeated if the password leaks. Add these to your Ansible
repo's .gitignore:
The encrypted vault.yml is safe to commit; the password file is not.
- Prefix vaulted variables with
vault_(e.g.vault_nas_samba_password), then map them to normal names ingroup_vars/all.yml:nas_samba_password: "{{ vault_nas_samba_password }}". This makes it obvious at a glance which values are secret and keepsno_logeasy to reason about. - Add
no_log: trueto tasks that handle secrets so they don't print to the terminal or logs. - Store the vault password itself in a real password manager (e.g. Vaultwarden).
Ref: Ansible โ Protecting sensitive data with Vault ยท Encrypting single values