What is Ansible Vault?
Vault encrypts sensitive variables so they can live in Git without exposing plaintext passwords, API keys, or cloud credentials.
Bad:
db_password: postgres123Good: store that value in an encrypted vault file and reference it from the playbook.
Create a vault file
ansible-vault create secrets.yml
# enter a vault passwordExample contents (written while the editor is open, then encrypted on save):
db_user: postgres
db_password: postgres123
db_name: productionansible-vault view secrets.yml
ansible-vault edit secrets.yml
ansible-vault rekey secrets.ymlUse vault vars in a playbook
---
- name: Database configuration
hosts: localhost
gather_facts: false
vars_files:
- secrets.yml
tasks:
- name: Print DB user
debug:
var: db_useransible-playbook db.yml --ask-vault-passEncrypt / decrypt existing files
ansible-vault encrypt secrets.yml
ansible-vault decrypt secrets.yml # avoid leaving decrypted files aroundEncrypt a single string
ansible-vault encrypt_string 'supersecret' --name 'db_password'Paste the !vault | block into a vars file.
Vault password file (CI)
echo 'my-vault-password' > vault.pass
chmod 600 vault.pass
ansible-playbook site.yml --vault-password-file vault.passNever commit vault.pass or decrypted secret files to Git. Add them to .gitignore.
Production layout
ansible-project/
├── playbooks/
├── group_vars/
│ └── all/
│ ├── vars.yml # plaintext references
│ └── vault.yml # encrypted
└── roles/
Pattern:
# vault.yml (encrypted)
vault_db_password: ...
# vars.yml
db_password: "{{ vault_db_password }}"Command cheat sheet
| Command | Purpose |
|---|---|
ansible-vault create | New encrypted file |
ansible-vault view | Read without decrypting to disk |
ansible-vault edit | Edit encrypted file |
ansible-vault encrypt / decrypt | Convert existing file |
ansible-vault rekey | Change password |
encrypt_string | Inline encrypted value |
Common secrets: DB passwords, AWS keys, SMTP creds, Jenkins tokens, API keys.