Mastering Ansible Vault: Practical Examples
Ansible Vault is a powerful feature that allows you to manage sensitive data, such as passwords, keys, and tokens, securely. It encrypts data using AES256 and stores it in a format that can be easily integrated into your Ansible playbooks. Let's dive into some practical examples to help you understand and use Ansible Vault effectively.
Getting Started with Ansible Vault
Before we begin, ensure you have Ansible installed. If not, you can install it using pip:
pip install ansible

Creating an Ansible Vault
To create a new Ansible Vault, use the following command:
ansible-vault create my_vault.yml
You'll be prompted to enter and verify a password. This password will be used to encrypt and decrypt the vault.

Storing Sensitive Data in Ansible Vault
Once you've created a vault, you can start storing sensitive data. Here's an example of storing database credentials:
| Variable | Value |
|---|---|
| db_user | vault_db_user |
| db_password | vault_db_password |
| db_name | my_database |
In your playbook, you can reference these variables like this:
vars_files:
- my_vault.yml

Encrypting Existing Variables
You can also encrypt existing variables using Ansible Vault. Here's how:
ansible-vault encrypt my_playbook.yml
This will prompt you to enter the password for the vault you want to use.
Viewing and Editing Ansible Vaults
To view the contents of a vault, use:
ansible-vault view my_vault.yml
To edit a vault, use:
ansible-vault edit my_vault.yml
Viewing and Editing Vaults with a Specific Password
If you have multiple vaults with different passwords, you can specify the password when viewing or editing:
ansible-vault view --ask-vault-pass my_vault.yml
Using Ansible Vault in Playbooks
When using Ansible Vault in playbooks, you can specify the vault password in the command line:
ansible-playbook -i localhost, --ask-vault-pass my_playbook.yml
Or, you can store the password in a file and use the ANSIBLE_VAULT_PASSWORD_FILE environment variable:
export ANSIBLE_VAULT_PASSWORD_FILE=/path/to/password/file
Best Practices
- Use unique, strong passwords for each vault.
- Store vault passwords securely, using tools like HashiCorp's Vault or AWS Secrets Manager.
- Regularly rotate your vault passwords.
- Use Ansible's
no_log: truedirective to prevent sensitive data from being logged.
Ansible Vault is a powerful tool that can greatly enhance the security of your Ansible playbooks. By understanding and effectively using Ansible Vault, you can manage sensitive data securely and efficiently.






















