Sometimes, you need to encrypt data such as passwords, API tokens, etc. in your python scripts to be able to share them securely.
ansible-vault
is not only for ansible, you can use it in your python scripts too:
#!/usr/bin/env python
import os
from ansible.constants import DEFAULT_VAULT_ID_MATCH
from ansible.parsing.vault import VaultLib, VaultSecret
vaulted_data = """$ANSIBLE_VAULT;1.2;AES256;main
65616638393834613334623633383233326465623863613531636463636636383532313538643832
3335333637363138663630663336333163326238323235610a343730666335346361633939333335
63306165323239636530366463626632613138666663373735626531386361303063613932373830
3136306435666131390a643434643836366135336662376538633861633637613663633962346565
34613966353462306134636537306636346662383932353332373636643633633061
"""
vault_pass = open('{}/.vault_pass'.format(os.environ.get('HOME'))).read().strip().encode('utf-8')
vault = VaultLib([
(DEFAULT_VAULT_ID_MATCH, VaultSecret(vault_pass))
])
cleartext_data = vault.decrypt(vaulted_data).decode('utf-8')
Some explanations:
vaulted_data
is my secret encrypted with ansible-vault
, the passphrase used to decrypt is stored in a separated ~/.vault_pass
file.
vault.decrypt()
is used to decrypt vaulted_data