示例#1
0
def decrypt_vault(filename,
                  vault_password=None,
                  vault_password_file=None,
                  vault_prompt=False):
    """
    filename: name of your encrypted file that needs decrypted.
    vault_password: key that will decrypt the vault.
    vault_password_file: file containing key that will decrypt the vault.
    vault_prompt: Force vault to prompt for a password if everything else fails.
    """

    loader = DataLoader()
    if vault_password:
        vault_secret = [([], VaultSecret(vault_password.encode()))]
    elif vault_password_file:
        vault_secret = CLI.setup_vault_secrets(loader=loader,
                                               vault_ids=[vault_password_file])
    else:
        vault_secret = CLI.setup_vault_secrets(loader=loader,
                                               vault_ids=[],
                                               auto_prompt=vault_prompt)

    vault = VaultLib(vault_secret)

    with open(filename) as f:
        unencrypted_yaml = vault.decrypt(f.read())
        unencrypted_yaml = yaml.safe_load(unencrypted_yaml)
        return unencrypted_yaml
 def __init__(self, inventory, ask_vault_pass, vault_password_files, vault_ids):
     from ansible.cli import CLI
     super(Inventory24, self).__init__()
     loader = DataLoader()
     if vault_ids or vault_password_files or ask_vault_pass:
         CLI.setup_vault_secrets(loader, vault_ids, vault_password_files, ask_vault_pass)
     self.inventory = ansible.inventory.manager.InventoryManager(loader=loader, sources=inventory)
     self.variable_manager = VariableManager(loader=loader)
     self.variable_manager.set_inventory(self.inventory)
示例#3
0
 def __init__(self, inventory, ask_vault_pass, vault_password_files,
              vault_ids):
     from ansible.cli import CLI
     super(Inventory24, self).__init__()
     loader = DataLoader()
     if vault_ids or vault_password_files or ask_vault_pass:
         CLI.setup_vault_secrets(loader, vault_ids, vault_password_files,
                                 ask_vault_pass)
     self.inventory = ansible.inventory.manager.InventoryManager(
         loader=loader, sources=inventory)
     self.variable_manager = VariableManager(loader=loader)
     self.variable_manager.set_inventory(self.inventory)
示例#4
0
def load_vaulted_pass(vault_password=None,
                      vault_password_file=None,
                      vault_prompt=False):
    loader = DataLoader()
    if vault_password:
        vault_secret = [([], VaultSecret(vault_password.encode()))]
    elif vault_password_file:
        vault_secret = CLI.setup_vault_secrets(loader=loader,
                                               vault_ids=[vault_password_file])
    else:
        vault_secret = CLI.setup_vault_secrets(loader=loader,
                                               vault_ids=[],
                                               auto_prompt=vault_prompt)
    vault = VaultLib(vault_secret)
    unencrypted_yaml = vault.decrypt(open("vaulted_password").read())
    unencrypted_yaml = yaml.safe_load(unencrypted_yaml)
    return unencrypted_yaml["password"]
示例#5
0
文件: ndmtk.py 项目: sebashmh/ndmtk
 def _load_auth_secrets(self, hosts=[], secrets=[]):
     for _safe, _lockpick in secrets:
         try:
             _safe_loader = DataLoader()
             _safe_lockpick = None
             try:
                 _safe_lockpick = CLI.read_vault_password_file(
                     _lockpick, loader=_safe_loader)
                 _safe_loader.set_vault_password(_safe_lockpick)
                 _safe_contents = _safe_loader.load_from_file(_safe)
             except:
                 _safe_lockpick = CLI.setup_vault_secrets(
                     _safe_loader, [_lockpick])
                 _safe_contents = _safe_loader.load_from_file(_safe)
             if 'credentials' not in _safe_contents:
                 return dict()
             #display.display(pprint.pformat(_safe_contents, indent=4), color='green');
             return _safe_contents['credentials']
         except Exception as e:
             display.display('[ERROR] ' + str(e), color='red')
     return dict()
def read_vault_yaml(path: str) -> dict:
    """Read YAML with vault-encrypted values.
    """
    # Read YAML without decrypting.
    raw_clean = open(path).read().replace('!vault', '')
    data = yaml.load(raw_clean, Loader=yaml.FullLoader)

    # Pop out PW file, if provided.
    pw_file = data.get('vault_password_file')
    pw_files = [pw_file] if pw_file else None

    loader = DataLoader()

    vault_secrets = CLI.setup_vault_secrets(
        loader=loader,
        vault_ids=C.DEFAULT_VAULT_IDENTITY_LIST,
        vault_password_files=pw_files,
    )

    loader.set_vault_secrets(vault_secrets)

    # Re-read with decryption.
    return loader.load_from_file(path)
示例#7
0

root = Path(__file__).resolve().parents[1]

with chdir(root):
    from ansible.cli import CLI
    from ansible.constants import DEFAULT_VAULT_IDENTITY_LIST
    from ansible.parsing.dataloader import DataLoader
    from ansible.parsing.vault import VaultLib

    data_loader = DataLoader()
    data_loader.set_basedir(root)

    vault_lib = VaultLib(
        CLI.setup_vault_secrets(data_loader,
                                DEFAULT_VAULT_IDENTITY_LIST,
                                auto_prompt=False))


def load_vault(path):
    with chdir(root):
        return yaml.load(vault_lib.decrypt(Path(path).read_text()),
                         Loader=yaml.SafeLoader)


class OutputFormat(str, Enum):
    BARE = "bare"
    ENV = "env"
    JSON = "json"

    def __str__(self):
示例#8
0
def run_module():
    module_args = dict(
        src=dict(type='str'),
        dest=dict(type='str'),
        password_file=dict(type='str', no_log=True),
        vartree=dict(type='dict', required=True),
        length=dict(type='int', required=False, default=20),
    )

    result = dict(changed=False, )

    module = AnsibleModule(argument_spec=module_args, supports_check_mode=True)

    if module.params['password_file']:
        # check if password file exists
        if not os.path.exists(module.params['password_file']):
            create_password_file(module.params['password_file'])
            result['changed'] = True

    # setup vault

    loader = DataLoader()

    if module.params['password_file']:
        vault_secret = CLI.setup_vault_secrets(
            loader=loader,
            vault_ids=C.DEFAULT_VAULT_IDENTITY_LIST,
            vault_password_files=[module.params['password_file']])
    else:
        vault_secret = CLI.setup_vault_secrets(
            loader=loader, vault_ids=C.DEFAULT_VAULT_IDENTITY_LIST)

    vault = VaultLib(vault_secret)
    vault_cli = VaultCLI(dict())

    # read input file
    if module.params['src']:
        print(module.params['src'])
        with open(module.params['src'], 'r') as stream:
            try:
                input = yaml.safe_load(stream)
            except yaml.YAMLError as exc:
                print("YAML is broken.")
                print(exc)

    else:
        input = module.params['vartree']

    walk_input(vault, vault_cli, input, module.params)
    yaml_out = yaml.dump(input, default_flow_style=False)

    # # setup vault
    # loader = DataLoader()
    # vault_secret = CLI.setup_vault_secrets(
    #         loader=loader,
    #         vault_ids=C.DEFAULT_VAULT_IDENTITY_LIST
    # )
    # vault = VaultLib(vault_secret)

    # encrypt it
    #    vault_out=vault.encrypt(yaml_out)

    # write to file
    ansible_facts_val = dict(vault_secrets=module.params['vartree'], )

    response = {
        "NAME": module.params['vartree'],
        #            "FILE": yaml_out,
        #            "VAULT": vault_out,
        #            "LENGTH": module.params['length'],
        #        module.params['vartree'],
    }

    module.exit_json(changed=result['changed'],
                     ansible_facts=ansible_facts_val,
                     vartree=module.params['vartree'])
示例#9
0
def populateModelFromInventory(model, inventory):
    if HOSTS not in model:
        model[HOSTS] = []
    if HOST_GROUPS not in model:
        model[HOST_GROUPS] = []

    loader = DataLoader()

    if inventoryHandler == PRE24:
        if VAULT_PASSWORD_FILE in inventory:
            vpf = inventory[VAULT_PASSWORD_FILE]
            if not os.path.exists(vpf):
                misc.ERROR(
                    "Ansible vault password file '{0}' does not exists!".
                    format(vpf))
            with open(vpf) as f:
                content = f.readlines()
            if len(content) == 0 or len(content[0].strip()) == 0:
                misc.ERROR(
                    "Invalid Ansible vault password file '{0}' content!".
                    format(vpf))
            loader.set_vault_password(content[0].strip())
        elif ASK_VAULT_PASSWORD in inventory and inventory[ASK_VAULT_PASSWORD]:
            prompt = "Password for Ansible inventory{0}: ".format(
                " '" + inventory[NAME] + "'" if NAME in inventory else "")
            content = getpass.getpass(prompt)
            loader.set_vault_password(content.strip())
        variable_manager = VariableManager()
        try:
            inventory = Inventory(loader=loader,
                                  variable_manager=variable_manager,
                                  host_list=inventory[FILE])
        except Exception as e:
            misc.ERROR(str(e))
        variable_manager.set_inventory(inventory)
        hosts = inventory.get_hosts()
    else:
        if VAULT_PASSWORD_FILE in inventory:
            from ansible.cli import CLI
            vpf = inventory[VAULT_PASSWORD_FILE]
            if not os.path.exists(vpf):
                misc.ERROR(
                    "Ansible vault password file '{0}' does not exists!".
                    format(vpf))
            CLI.setup_vault_secrets(loader=loader,
                                    vault_ids=[],
                                    vault_password_files=[vpf],
                                    ask_vault_pass=False,
                                    create_new_password=False)
        elif ASK_VAULT_PASSWORD in inventory and inventory[ASK_VAULT_PASSWORD]:
            from ansible.cli import CLI
            CLI.setup_vault_secrets(loader=loader,
                                    vault_ids=[],
                                    vault_password_files=[],
                                    ask_vault_pass=True,
                                    create_new_password=False)

        inventory = InventoryManager(loader=loader, sources=inventory[FILE])
        variable_manager = VariableManager(loader=loader, inventory=inventory)
        hosts = inventory.get_hosts()

    existingHosts = set(map(lambda x: x[NAME], model[HOSTS]))
    #print(existingHosts)
    for host in hosts:
        if not host.name in existingHosts:
            h = {}
            h[NAME] = host.name.encode('utf8')
            for key in host.vars:
                if key.startswith('ansible_'):
                    key2 = key[len('ansible_'):].encode('utf8')
                    #print "key2:{}".format(key2)
                    if not key2.startswith("ssh_"):
                        key2 = "ssh_" + key2
                    #print "key2b:{}".format(key2)
                    if isinstance(host.vars[key], basestring):
                        h[key2] = host.vars[key].encode('utf8')
                    else:
                        h[key2] = host.vars[key]
                    # ssh_private_key_file may be relative to source inventory file. Set it absolute
                    if key2 == SSH_PRIVATE_FILE_FILE:
                        p = h[key2]
                        if not os.path.isabs(p):
                            h[key2] = os.path.normpath(
                                os.path.join(os.path.dirname(inventory[FILE]),
                                             p))
            model[HOSTS].append(h)

    existingHostGroups = set(map(lambda x: x[NAME], model[HOST_GROUPS]))
    #print(existingHostGroups)
    if inventoryHandler == PRE24:
        hvars = variable_manager.get_vars(loader=loader,
                                          host=hosts[0],
                                          include_hostvars=False)
    else:
        hvars = variable_manager.get_vars(host=hosts[0],
                                          include_hostvars=False)
    groups = hvars[GROUPS]
    for grpName in groups:
        if grpName != 'all' and grpName != 'ungrouped' and (
                not grpName in existingHostGroups):
            grp = {}
            grp[NAME] = grpName.encode('utf8')
            l = []
            for h in groups[grpName]:
                l.append(h.encode('utf8'))
            grp[HOSTS] = l
            model[HOST_GROUPS].append(grp)