Skip to content

Instantly share code, notes, and snippets.

@nimro27
Last active March 13, 2025 10:31
Show Gist options
  • Save nimro27/7d4dd9df9d7ade75c7e6a156cc95e8e6 to your computer and use it in GitHub Desktop.
Save nimro27/7d4dd9df9d7ade75c7e6a156cc95e8e6 to your computer and use it in GitHub Desktop.
Ansible vault script using git credential-cache
#!/usr/bin/env python3.8
"""
Author: Johannes Zumthurm <[email protected]>
This script allows the ansible vault password for running playbooks to be temporarily
stored in the git credential-cache. The git credential cache can be configured using:
git config credential.helper 'cache --timeout=3600'
Where the timeout is given in seconds.
To use the script eiter pass it in to the playbook command:
ansible-playbook my-playbook.yml --vault-password-file vault_cred_cache
Or configure the following line in the ansible.cfg file:
[defaults]
vault_password_file = ./vault_cred_cache
When the script cannot find the password it will prompt the user just as using
--ask-vault-password would. It then stores the password in the credential-cache.
"""
import subprocess, getpass, sys
def get_password():
cred = "username=ansible\nprotocol=https\nhost=vault\n"
res = subprocess.run(["git", "credential-cache", "get"], input=cred.encode(), capture_output=True)
for line in res.stdout.decode().splitlines():
if line.startswith("password="):
return line.split("=", 1)[1]
return None
def store_password(pwd):
cred = f"username=ansible\nprotocol=https\nhost=vault\npassword={pwd}\n"
subprocess.run(["git", "credential-cache", "store"], input=cred.encode())
pwd = get_password()
if not pwd:
pwd = getpass.getpass("Enter vault password: ")
store_password(pwd)
sys.stdout.write(f"{pwd}\n")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment