How to setup Ansible Vault #
Here’s a little guide on how I setup Ansible Vault for my Ansible playbook repository. It’s surprisingly simple and now all of my secrets are encrypted.
Setting Up Ansible Vault #
1. Create the Directory Structure #
First, create the standard Ansible directory structure for group variables:
mkdir -p group_vars/all
2. Create Your Vault File #
Create a vault file to store your encrypted credentials:
touch group_vars/all/vault.yml
3. Add Your Credentials #
Edit the vault file and add your sensitive data in standard YAML format:
# group_vars/all/vault.yml
admin_password: "Password123!"
database_password: "MySecretDBPass"
api_key: "your-secret-api-key"
ssl_certificate_key: "-----BEGIN PRIVATE KEY-----\n..."
4. Encrypt the File #
Now encrypt the entire file with a password:
ansible-vault encrypt group_vars/all/vault.yml
You’ll be prompted to enter a password. Choose a strong password and remember it - you’ll need it to decrypt the file later.
After encryption, your file will look something like this:
$ANSIBLE_VAULT;1.1;AES256
66386439653237336464643735633366643530623638386165366566613135643665373731656131
3665626464313135643665373731656131366338616433653339336464643735633366643530623638
...
5. Using Encrypted Variables #
To use the encrypted variables in your playbooks, simply reference them by name:
- name: Configure database
mysql_user:
name: admin
password: "{{ admin_password }}"
priv: "*.*:ALL"
Working with Encrypted Files #
Viewing Vault Contents #
To view the contents of an encrypted vault file:
ansible-vault view group_vars/all/vault.yml
Editing Vault Contents #
To edit an encrypted vault file:
ansible-vault edit group_vars/all/vault.yml
This command will decrypt the file, open it in your default editor, and re-encrypt it when you save and exit.
Running Playbooks with Vault #
When running playbooks that use encrypted variables, you need to provide the vault password:
ansible-playbook -i inventory.ini playbook.yml --ask-vault-pass
For automated deployments, you can also use a password file (like in a CI/CD runner):
ansible-playbook -i inventory.ini playbook.yml --vault-password-file .vault_pass