So you want to use secrets stored in Ansible Vault in your Python apps. Let’s see how to do that. If you later find this article useful take a look at the disclaimer for information on how to thank me.
If you are not familiar with Ansible Vault, go over the brief introduction below.
Store secrets in Ansible Vault
So, you might already know that storing secrets in your source code is bad. Yet, your app uses secrets and must store them in source code repository. What can you do? You can opt for a fully fledged secret storage solution (e.g. HashiCorp Vault). Yet, this is an overkill for a simple app using secrets. What can you do? The simplest thing that comes to mind is encrypting the secrets and keeping them encrypted under source control. Ansible Vault allows just that.
Storing secrets in Ansible Vault step by step
vault.ymlfile and add your secrets in yaml format as below:
secret_name1: val1 secret_name2: val2
- Next, create
multi_password_file. Add the password to the vault to the file and add it to
.gitignore. This is the password which will encrypt the vault. Remember that if you lose this password file, you won’t be able to decrypt your Ansible vault.
ansible. Installing it will install
ansible-vaultbinary as well and add it to your PATH.
ansible-vault encrypt vault.yml --vault-password-file multi_password_fileto encrypt your vault. Afterwards,
vault.ymlwill start with
$ANSIBLE_VAULT;1.1;AES256and will contain just numbers.
ansible-vault decrypt vault.yml --vault-password-file multi_password_fileto decrypt the vault. Then you’ll see your secrets in clear text. You can safely commit
vault.ymlto source code repository.
Read Ansible Vault in Python
Now, let’s assume you want to use the secrets from Ansible Vault in your Python app or script. How can you read it? You can do that using
ansible-vault package. Then use below Python code for reading the vault:
from pathlib import Path from ansible_vault import Vault vault = Vault((Path('multi_password_file').read_text())) data = vault.load(open('vault.yml').read())
data is Python dictionary which contains the Ansible vault secrets in clear text which your app/script can use.
That’s it about using
Ansible Vault in Python. As always feel free to share. If you found this article useful, take a look at the disclaimer for information on how to thank me.
You can also find below articles useful:
Recommended Kubernetes books on Amazon: