Securing Infrastructure with Ansible Vault
Storing sensitive data such as passwords, API keys, and certificates in plaintext is a major security risk, especially when using version control systems like Git. Ansible Vault provides a simple way to encrypt your sensitive data and decrypt it on the fly during playbook execution.
🏗️ Core Concepts
To understand Ansible Vault, it's important to grasp these primary terminologies:
- Encryption: Scrambling plaintext (readable data) into ciphertext (unreadable data).
- Decryption: Converting ciphertext back into its original plaintext format.
- Cryptography: The technical practice of securing information thru encryption techniques.
- Vault Password: The single "Master Key" used to both encrypt and decrypt your vaulted files.
🛠️ Essential Vault Operations (CLI)
Ansible provides a dedicated CLI tool, ansible-vault, to manage your encrypted secrets.
1. Creating and Editing Secrets
Use these commands to manage vaulted files without ever exposing them as plaintext:
| Task | Command | Description |
|---|---|---|
| Create | ansible-vault create secret.yml | Opens an editor to create a new encrypted file. |
| Edit | ansible-vault edit secret.yml | Opens the file in an editor for secure modifications. |
| View | ansible-vault view secret.yml | Displays the decrypted contents without saving them. |
2. Managing Existing Files
You can encrypt existing files or change their master password:
| Task | Command | Description |
|---|---|---|
| Encrypt | ansible-vault encrypt site_vars.yml | Converts a plaintext file into a vaulted file. |
| Decrypt | ansible-vault decrypt site_vars.yml | Permanently converts a vaulted file back to plaintext. |
| Re-key | ansible-vault rekey secret.yml | Changes the vault password for that file. |
🚀 Running Playbooks with Vault
When your playbook depends on vaulted files, you must provide the vault password at execution time.
Method 1: Manual Prompt (Safest for Local Dev)
ansible-playbook site.yml --ask-vault-passMethod 2: Password File (Best for CI/CD)
Create a .vault_pass file (and add it to .gitignore!) then reference it:
ansible-playbook site.yml --vault-password-file .vault_pass🔒 Security Best Practices
[!CAUTION] Never commit your Vault Password! Ensure your password file or environment variables containing the master key are NEVER pushed to Git. Always add them to your
.gitignore.
- Keep Secrets Separate: Organize your variables so that only sensitive data (passwords, keys) is in a vaulted file. Non-sensitive data should stay in plaintext.
- Use Group Variables: Store your vaulted files in
group_vars/all/vault.ymlfor easy access across the project. - Password Rotation: Regularly "Re-key" your sensitive files to maintain high-security standards.