39 lines
1.2 KiB
Python
39 lines
1.2 KiB
Python
"""Helper functions for Ansible vault operations."""
|
|
import os
|
|
import tempfile
|
|
import subprocess
|
|
from pathlib import Path
|
|
|
|
def decrypt_vault_file(vault_file_path):
|
|
"""
|
|
Decrypt an Ansible vault file using the password from environment variables.
|
|
|
|
Args:
|
|
vault_file_path (str): Path to the encrypted vault file
|
|
|
|
Returns:
|
|
str: Decrypted contents of the vault file
|
|
"""
|
|
vault_pass = os.getenv('ANSIBLE_VAULT_PASSWORD')
|
|
if not vault_pass:
|
|
raise ValueError("ANSIBLE_VAULT_PASSWORD environment variable not set")
|
|
|
|
with tempfile.NamedTemporaryFile(mode='w', delete=False) as vault_pass_file:
|
|
vault_pass_file.write(vault_pass)
|
|
vault_pass_file.flush()
|
|
|
|
try:
|
|
result = subprocess.run(
|
|
['ansible-vault', 'view', str(vault_file_path)],
|
|
capture_output=True,
|
|
text=True,
|
|
env={**os.environ, 'ANSIBLE_VAULT_PASSWORD_FILE': vault_pass_file.name}
|
|
)
|
|
|
|
if result.returncode != 0:
|
|
raise Exception(f"Failed to decrypt vault: {result.stderr}")
|
|
|
|
return result.stdout
|
|
|
|
finally:
|
|
os.unlink(vault_pass_file.name) |