How to view/decrypt Ansible vault credentials files from within a Python script?

I’m trying to figure out how to provide the following facilities to a Python script so that it can:

  1. Import Ansible Python modules
  2. Open up my defined ansible.cfg and read vault_password_file variable
  3. Read vault_password_file and temporarily store in a Python variable
  4. Decrypt a referenced Ansible vaulted file

I found this code via google but it did not appear to work when I tried it:

import ansible.utils

bar = dict()

bar = ansible.utils._load_vars_from_path("secrets.yml", results=bar, vault_password="password")

print bar

Throws this error:

$ python
Traceback (most recent call last):
  File "", line 5, in <module>
    bar = ansible.utils._load_vars_from_path("credentials.vault", results=bar, vault_password="password")
AttributeError: 'module' object has no attribute '_load_vars_from_path'

When I investigated this I saw no indications of this function in any Ansible related files, leading me to believe that this method no longer worked with some newer version(s) of Ansible.

Bottom line is that I’d like some method for importing Ansible libraries/modules from a Python script, so that I can interact with ansible-vault managed files programmatically from Python.


Consider using the the ansible-vault package

Install it by:

$ pip install ansible-vault

and then it is as simple as:

from ansible_vault import Vault

vault = Vault('password')
print vault.load(open('/path/to/your/vault.yml').read())

To use the ansible code directly look at the source of that package. The simplest would be:

Ansible <= 2.3

from ansible.parsing.vault import VaultLib

vault = VaultLib('password')

Ansible >= 2.4

from ansible.constants import DEFAULT_VAULT_ID_MATCH
from ansible.parsing.vault import VaultLib, VaultSecret

vault = VaultLib([(DEFAULT_VAULT_ID_MATCH, VaultSecret('password'.encode()))])

The amount of source code is equal but the package provides automatic yaml parsing + handling of both Ansible versions.

Source : Link , Question Author : slm , Answer Author : Martin Thoma

Leave a Comment