Bradley Kirton's Blog

Published on Feb. 12, 2025

Go home

Storing ansible vault keys in your system keyring

Below is a method for storing ansible vault keys within your system's keyring. This assumes you have Python installed along with the keyring package.

1. Create the Vault Key Client Script

Create a new file named vault-keyring-client with the following content and make it executable (chmod +x vault-keyring-client):

#!/usr/bin/env python
import argparse
import platform

import keyring

if platform.system() == "Linux":
    from keyring.backends import SecretService as KeyringBackend
elif platform.system() == "Darwin":
    from keyring.backends import macOS as KeyringBackend
else:
    raise RuntimeError("Only MacOS and Linux are supported")


parser = argparse.ArgumentParser()
parser.add_argument("--vault-id", help="The vault identifier.", required=True)
args = parser.parse_args()

keyring.set_keyring(KeyringBackend.Keyring())
credential = keyring.get_credential(args.vault_id, "")

if credential:
    print(credential.password)
else:
    exit(1)

2. Store Your Vault Key

Add your vault key to the keyring. Note you could specify the backend based on your system preference.

keyring -b keyring.backends.SecretService.Keyring get your_vault_name ''

When prompted, enter your vault password. Replace yourvaultname with a meaningful identifier for your vault.

3. Use the Vault Key with Ansible

Now you can use the stored key with Ansible commands:

ansible-vault --vault-id your_vault_name@/path/to/vault-keyring-client decrypt secrets.yml
ansible-playbook --vault-id your_vault_name@/path/to/vault-keyring-client playbook.yml