Skip to content

Instantly share code, notes, and snippets.

@jordiclariana
Created February 22, 2019 15:16
Show Gist options
  • Save jordiclariana/9bee4090dc9a568e2d4511958d47d452 to your computer and use it in GitHub Desktop.
Save jordiclariana/9bee4090dc9a568e2d4511958d47d452 to your computer and use it in GitHub Desktop.
Rekey Vaulted YAML values
#!/usr/bin/env python2
from ansible.parsing import vault
from ansible.constants import DEFAULT_VAULT_ID_MATCH
import re
import os
import click
@click.command()
@click.argument('src_file', required=True, type=click.File('r+'))
@click.option('--src-secret', required=True, help='Current Vault password file to decrypt the file')
@click.option('--dst-secret', required=True, help='New Vault password file to encrypt the file')
def main(src_file, src_secret, dst_secret):
OLD_PASS_FILE = os.path.expanduser(src_secret)
with open(OLD_PASS_FILE, 'r') as vault_pass_file:
VAULTPASS = vault_pass_file.readline().strip()
old_v = vault.VaultLib(
[(DEFAULT_VAULT_ID_MATCH, vault.VaultSecret(VAULTPASS))])
NEW_PASS_FILE = os.path.expanduser(dst_secret)
with open(NEW_PASS_FILE, 'r') as vault_pass_file:
VAULTPASS = vault_pass_file.readline().strip()
new_v = vault.VaultLib(
[(DEFAULT_VAULT_ID_MATCH, vault.VaultSecret(VAULTPASS))])
vars_file = src_file.readlines()
src_file.seek(0)
is_vault = False
match = None
vault_pattern = re.compile(r"^( *)\$ANSIBLE_VAULT")
indent_pattern = re.compile(r"^( *)")
new_vars_file = ""
for line in vars_file:
if not is_vault:
match = vault_pattern.match(line)
if match:
is_vault = True
indent = match.group(1)
encvar = line.lstrip()
else:
new_vars_file = new_vars_file + line
else:
match = indent_pattern.match(line)
if match.group(1) == indent:
encvar = encvar + line.lstrip()
else:
encvar = new_v.encrypt(old_v.decrypt(encvar))
new_vars_file = new_vars_file + \
''.join(indent+line for line in encvar.splitlines(True))
is_vault = False
match = None
new_vars_file = new_vars_file + line
src_file.truncate()
src_file.write(new_vars_file)
src_file.close()
if __name__ == "__main__":
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment