Skip to content
tomoh1r edited this page Feb 6, 2021 · 3 revisions

Samples

Around VaultLib

Use ANSIBLE_VAULT_PASSWORD_FILE

Create your own VaultLib and use it with vault_lib option.

See test_password.py.

from pathlib import Path
from ansible_vault import Vault, VaultLibABC, make_secrets

class MyVaultLib(VaultLibABC):
    def __init__(self):
        fpath = os.environ.get("ANSIBLE_VAULT_PASSWORD_FILE")
        password = open(fpath).read().strip().encode("utf-8")
        self.vlib = VaultLib(make_secrets(password))

    def encrypt(self, plaintext):
        return self.vlib.encrypt(plaintext)

    def decrypt(self, vaulttext):
        return self.vlib.decrypt(vaulttext)


fpath = Path("path") / "to" / "vaulttext.txt"
Vault(vault_lib=MyVaultLib()).load(open(fpath).read())

Around file types

PlainText

Use load_raw/dump_raw method.

See test_plain.py.

Read from the encrypted file.

from pathlib import Path
from ansible_vault import Vault

fpath = Path("path") / "to" / "vaulttext.txt"
plaintext = Vault("password").load_raw(open(fpath).read())

Write to the file.

from pathlib import Path
from ansible_vault import Vault

input_str = "hello, world"

fpath = Path("path") / "to" / "vaulttext.txt"
with open(fpath, "w") as fp:
    Vault("password").dump_raw(input_str.encode("utf-8"), fp)

JSON

Use load_raw/dump_raw method and wrap with json module.

See test_json.py.

Read from the encrypted JSON file.

import json
from pathlib import Path
from ansible_vault import Vault

fpath = Path("path") / "to" / "vaulttext.txt"
json_data = json.loads(Vault("password").load_raw(open(fpath).read()))

Write JSON data to the file.

import json
from pathlib import Path
from ansible_vault import Vault

json_data = {"foo": "bar"}

fpath = Path("path") / "to" / "vaulttext.txt"
with open(fpath, "w") as fp:
    Vault("password").dump_raw(json.dumps(json_data).encode("utf-8"), fp)
Clone this wiki locally