If you are not familiar with the Ansible Vault, check out my article Getting Started with the Ansible Vault.
Let's say you used the ansible-vault create command to create an Ansible Vault encrypted file in the group_vars/all directory named vault.yml.
ansible-vault create group_vars/all/vault.yml
And let's say the vault.yml files contains the postgres_pw variable.
postgres_pw: foo
And you have a playbook that contains the postgres_pw variable.
---
- hosts: postgres
tasks:
- community.postgresql.postgresql_query:
db: mydb
login_user: john.doe
login_password: "{{ postgres_pw }}"
query: SELECT * FROM mytable
...
In this scenario, the vault.yml file will need to be decrypted when running the postgres playbook. This is often done by using the --vault-password-file command line option and pointing to a TXT file that contains the password that can be used to decrypt the vault.yml file, perhaps like this. Let's say the password to decrypt the vault.yml file is "bar".
ansible-playbook postgres.yml --inventory inventory.yml --vault-password-file password.txt
This can be a bit confusing at times, as there are two different passwords in this super common example.
- foo = Postgres password
- bar = Ansible Vault password
This is fine and dandy if you are the only person running the Ansible playbook, but if you want one of your colleagues to run the playbook, you'd have to give the colleague the password and have them create their own TXT file that contains the password, or put the TXT file in a shared location. This is just asking for problems and sounds like a situation that inevitabely will lead to the TXT file getting leaked and the password being totally compromised.
One alternative solution to this would be to create a script that returns the Ansible Vault password, which is "bar" in this example. Ideally, you should probably obtain the value from a secret, such as an Amazon Web Services (AWS) Secret or a Hashicorp Vault Secret. In this example, the Python script gets the Ansible Vault password from a Hashicorp Vault Secret.
#!/usr/bin/python3
import requests
response = requests.get(
f"https://vault.example.com/v1/my_team/data/ansible_vault",
headers={"X-Vault-Token": "abc123"}
)
data = response.json()['data']['data']
print(data[args.key])
Let's ensure the script is allowed to be exected.
chmod +x ansibleVault.py
Now, test the script and it should output the Ansible Vault password.
~]$ ./ansibleVault.py
bar
Now, you should be able to use the ansibleVault.py script instead of having "bar" in a TXT file. Going back to the earlier example, we simply run the same exact ansible-playbook command, but instead of using the TXT file that contains "bar" we used the ansibleVault.py script which outputs "bar".
ansible-playbook postgres.yml --inventory inventory.yml --vault-password-file ./ansibleVault.py
Did you find this article helpful?
If so, consider buying me a coffee over at