References for using Ansible-Vault's APIs in a Python script

Is there some development documentation where I can implement the encrypt / decrypt functionality that the ansible-vault CLI provides via a python API that does not involve using subprocess ?

I have a very simple REST API where I wish to add dedicated secrets to some vault.yml files in the inventory directory and wish to encrypt and decrypt the files after writing to the file and before writing to the file respectively.

I’ve not actually tried it, but tomoh1r/ansible-vault might fit the bill.

from ansible_vault import Vault

vault = Vault('password')
vault.dump(data, open('vault.yml', 'w'))

Note that in spite of its name, the project isn’t part of Ansible.

EDIT: I was curious and have now tried it. I did not run pip install ansible-vault as it wanted to download the full ansible package, so I created a virtualenv as so:

$ python3 -mvenv va
$ source va/bin/activate
$ pip install ansible-core
$ pip install setuptools  # required by a-v package
$ cd va/
$ git clone

$ ./  # my test program as above
$ ansible-vault view vault.yml  # showed me my data

EDIT2: getting old sucks. It turns out I blogged about this four years ago.


Note that the vault API is not public and subject to change w/o deprecation, while this will work for now, it is not guaranteed to work for the future.

Rather than trying to use the internal API (which, as @bcoca points out is not public and subject to change), you could take the approach of GitHub - utoddl/av-filter: Filter for "ansible-vault"ing YAML Data Values and use the CLI interface to ansible-vault. I’m using it in that case on named strings rather than whole file vaulting, but the changes would be trivial.

This topic was automatically closed 30 days after the last reply. New replies are no longer allowed.