|
| 1 | +"""Module for custom click types regarding to ansible""" |
| 2 | + |
| 3 | +import click |
| 4 | +import os |
| 5 | +import yaml |
| 6 | + |
| 7 | +from ansible.errors import AnsibleError |
| 8 | +from ansible_vault import Vault |
| 9 | +from yaml import SafeLoader |
| 10 | + |
| 11 | + |
| 12 | +class AnsibleVaultParamType(click.ParamType): |
| 13 | + """Provide a custom click type for ansible vaults. |
| 14 | +
|
| 15 | + This custom click type provides managing passed values in a given vault. |
| 16 | + * decrypt vault |
| 17 | + * save passed value |
| 18 | + * encrypt vault |
| 19 | + """ |
| 20 | + name = 'vault' |
| 21 | + |
| 22 | + vault = str |
| 23 | + secret = str |
| 24 | + path = str |
| 25 | + |
| 26 | + def __init__(self, vault: str, secret: str, path: str): |
| 27 | + """Create a AnsibleVaultParamType object. |
| 28 | +
|
| 29 | + This method takes three arguments that are necessary to initialize a AnsibleVaultParamType object. |
| 30 | +
|
| 31 | + :param vault: Path to the vault file. |
| 32 | + :type vault: str |
| 33 | + :param secret: Name of the Environement variable that stores the vault passphrase. |
| 34 | + :type secret: str |
| 35 | + :param path: Path where the passed value should be saved in dotted notation. |
| 36 | + :type path: str |
| 37 | + """ |
| 38 | + try: |
| 39 | + s = os.getenv(secret) |
| 40 | + self.v = Vault(s) |
| 41 | + except (TypeError, ValueError): |
| 42 | + self.fail('Environment variable \'{0}\' not set.'.format(secret)) |
| 43 | + |
| 44 | + self.vault = vault |
| 45 | + self.path = path |
| 46 | + |
| 47 | + super(AnsibleVaultParamType, self).__init__() |
| 48 | + |
| 49 | + def convert(self, value, param, ctx): |
| 50 | + """Open vault and save vaule at the given path. |
| 51 | +
|
| 52 | + :param value: the value passed |
| 53 | + :type value: str |
| 54 | + :param param: the parameter that we declared |
| 55 | + :type param: str |
| 56 | + :param ctx: context of the command |
| 57 | + :type ctx: str |
| 58 | + :return: the passed value as a checked semver |
| 59 | + :rtype: str |
| 60 | + """ |
| 61 | + data = {} |
| 62 | + try: |
| 63 | + if os.path.exists(self.vault): |
| 64 | + data = self.v.load(open(self.vault).read()) |
| 65 | + except AnsibleError as e: |
| 66 | + if 'not vault encrypted data' in str(e): |
| 67 | + data = yaml.load(open(self.vault).read(), SafeLoader) or {} |
| 68 | + except Exception as e: |
| 69 | + self.fail('Decryption failed: {0}'.format(str(e)), param, ctx) |
| 70 | + |
| 71 | + data = self._populate_data(data, self.path.split('.'), value) |
| 72 | + with open(self.vault, "w") as f: |
| 73 | + yaml.dump(data, f) |
| 74 | + |
| 75 | + try: |
| 76 | + self.v.dump(data, open(self.vault, 'w')) |
| 77 | + except: # noqa: E722 |
| 78 | + self.fail('Error while encrypting data', param, ctx) |
| 79 | + |
| 80 | + return self.path |
| 81 | + |
| 82 | + def _populate_data(self, input={}, keys=[], value=None): |
| 83 | + """Save value at the desired position in vault. |
| 84 | +
|
| 85 | + This method takes vault data, a list of keys where to store the value. |
| 86 | +
|
| 87 | + :param input: The dictionary of vault data, defaults to {} |
| 88 | + :type input: dict, optional |
| 89 | + :param keys: List of keys that describe the desired position in vault, defaults to [] |
| 90 | + :type keys: list, optional |
| 91 | + :param value: The value to store in vault, defaults to None |
| 92 | + :type value: str, optional |
| 93 | + :return: The vault data extended by `value` at the desired position. |
| 94 | + :rtype: dict |
| 95 | + """ |
| 96 | + data = input.copy() |
| 97 | + |
| 98 | + if keys: |
| 99 | + key = keys[0] |
| 100 | + |
| 101 | + if isinstance(key, str) and len(keys) > 1: |
| 102 | + if key in data: |
| 103 | + data[key].update(self._populate_data({}, keys[1:], value)) |
| 104 | + else: |
| 105 | + data[key] = {} |
| 106 | + data[key].update(self._populate_data({}, keys[1:], value)) |
| 107 | + elif isinstance(key, str): |
| 108 | + if key in data: |
| 109 | + data[key].update(self._populate_data({}, keys[1:], value)) |
| 110 | + else: |
| 111 | + data[key] = value |
| 112 | + return data |
0 commit comments