ansible-vault Python Library

4.1.0 · active · verified Tue Apr 14

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

Install

Imports

Quickstart

This quickstart demonstrates how to initialize the `Vault` object with a password, then encrypt and decrypt a simple string. It also shows how to use `Vault.dump()` to write encrypted YAML content to a file and `Vault.load()` to read and decrypt it.

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)

view raw JSON →