ansible-vault Python Library
ansible-vault is a Python library designed for programmatic interaction with Ansible Vault encrypted files and strings. It provides a compatible interface to encrypt and decrypt data, allowing Python applications to read from or write to Ansible Vault YAML files. The current version is 4.1.0, and it is actively maintained as a community fork of the original `sivel/ansible-vault` project.
Warnings
- gotcha This `ansible-vault` package (`tomoh1r/ansible-vault`) is a fork of the original, unmaintained `sivel/ansible-vault`. Users might mistakenly install or confuse it with the unmaintained version.
- gotcha The `Vault` constructor expects a bytes object for the password, not a plain string. Passing a string will result in a `TypeError`.
- gotcha When encrypting or decrypting YAML, `Vault.dump()` and `Vault.load()` operate on file-like objects (opened file handles) directly, not file paths.
Install
-
pip install ansible-vault
Imports
- Vault
from ansible_vault import Vault
Quickstart
import os
from ansible_vault import Vault
# Get password from environment for security, or provide directly
vault_password = os.environ.get('ANSIBLE_VAULT_PASSWORD', 'your_secret_password').encode()
vault = Vault(vault_password)
# 1. Encrypt and decrypt a string
original_string = 'my_secret_data'
encrypted_string = vault.encrypt(original_string)
decrypted_string = vault.decrypt(encrypted_string)
print(f"Original: {original_string}")
print(f"Encrypted: {encrypted_string[:20]}...") # Truncate for display
print(f"Decrypted: {decrypted_string}")
# 2. Encrypt and decrypt a YAML file
# Create a dummy vault file
file_content = {
'database': {
'host': 'localhost',
'username': 'dbuser',
'password': 'dbpassword123'
},
'api_key': 'supersecretapikey'
}
vault_file_path = 'my_vault.yml'
with open(vault_file_path, 'w') as f:
vault.dump(file_content, f)
print(f"\nVault YAML file '{vault_file_path}' created and encrypted.")
# Load and decrypt the YAML file
with open(vault_file_path, 'r') as f:
decrypted_yaml_content = vault.load(f)
print(f"Decrypted YAML content: {decrypted_yaml_content}")
# Clean up the dummy file
os.remove(vault_file_path)