Skip to content

Instantly share code, notes, and snippets.

@0x9900
Created May 25, 2016 06:43
Show Gist options
  • Save 0x9900/875f082195ef9a7c83017668784d1360 to your computer and use it in GitHub Desktop.
Save 0x9900/875f082195ef9a7c83017668784d1360 to your computer and use it in GitHub Desktop.
Use a file and a password to generate a cryptographic key for Ansible Vault. (the password can be saved in the Mac Keychain.
#!/usr/bin/env python2.7
#
# Author: Fred Cirera <[email protected]>
# Module: vault-password.py
#
""" This script requires the ``keyring`` python module
Add a [vault] section to your ansible.cfg file,
the options are
- token (required)
- keyfile (required)
- save_password (optional)
Example:
[vault]
token = foobar
keyfile = ~/KeyFile.dat
save_password = yes
It is also a good idea to the variable vault_password_file
[defaults]
...
vault_password_file = /path/to/vault-keyring.py
"""
import getpass
import hashlib
import hmac
import keyring
import os
import sys
from functools import partial
import ansible.constants as C
def get_key(token, program, save_password):
"""Try to find the encryption key for that token in the keyring. If
the key cannot be found prompt the user.
"""
key = keyring.get_password(program, token)
# the key hasn't been found in the keyring. Request for a new one.
if not key:
key = getpass.getpass('Encryption key: ')
if save_password:
try:
keyring.set_password(program, token, key)
except keyring.errors.PasswordSetError as exp:
sys.stderr.write(exp + '\n')
return str(key)
def main():
parser, _ = C.load_config_file()
if not parser.has_section('vault'):
sys.stderr.write('No [vault] section configured\n')
sys.exit(1)
try:
token = parser.get('vault', 'token')
keyfile = parser.get('vault', 'keyfile')
except C.configparser.NoOptionError as exp:
sys.stderr.write(exp + '\n')
sys.exit(1)
try:
save_password = parser.get('vault', 'save_password')
except C.configparser.NoOptionError:
save_password = False
except C.configparser.ValueError as exp:
sys.stderr.write(exp + '\n')
sys.exit(1)
keyfile = os.path.expanduser(keyfile)
program_name = os.path.basename(sys.argv[0])
key = get_key(token, program_name, save_password)
# Generate a password based on a cryptographic hash functions.
with open(keyfile) as fd:
hasher = hmac.new(key, digestmod=hashlib.sha256)
for buf in iter(partial(fd.read, 4096), ''):
hasher.update(buf)
sys.stdout.write(hasher.hexdigest() + '\n')
if __name__ == '__main__':
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment