如何在Python脚本中查看/解密Ansible保险库凭证文件?

时间:2017-05-23 18:16:04

标签: python encryption ansible ansible-vault

我试图弄清楚如何为Python脚本提供以下功能,以便它可以:

  1. 导入Ansible Python模块
  2. 打开我定义的ansible.cfg并阅读vault_password_file变量
  3. 阅读vault_password_file并暂时存储在Python变量中
  4. 解密引用的Ansible存储文件
  5. 我找到了this code via google,但在我尝试时似乎没有效果:

    import ansible.utils
    
    bar = dict()
    
    bar = ansible.utils._load_vars_from_path("secrets.yml", results=bar, vault_password="password")
    
    print bar
    

    引发此错误:

    $ python ansible-vault-ex.py
    Traceback (most recent call last):
      File "ansible-vault-ex.py", line 5, in <module>
        bar = ansible.utils._load_vars_from_path("credentials.vault", results=bar, vault_password="password")
    AttributeError: 'module' object has no attribute '_load_vars_from_path'
    

    当我调查这个时,我在任何Ansible相关文件中都没有看到这个函数的迹象,这让我相信这个方法不再适用于Ansible的一些新版本。

    总的来说,我喜欢从Python脚本导入Ansible库/模块的一些方法,以便我可以从Python以编程方式与ansible-vault托管文件进行交互。

7 个答案:

答案 0 :(得分:7)

考虑使用ansible-vault package

按以下方式安装:

$ pip install ansible-vault

然后它就像:

一样简单
from ansible_vault import Vault

vault = Vault('password')
print vault.load(open('/path/to/your/vault.yml').read())

要直接使用ansible代码,请查看该包的source。最简单的是:

Ansible &lt; = 2.3

from ansible.parsing.vault import VaultLib

vault = VaultLib('password')
print vault.decrypt(open('/path/to/vault.yml').read())

Ansible &gt; = 2.4

from ansible.constants import DEFAULT_VAULT_ID_MATCH
from ansible.parsing.vault import VaultLib
from ansible.parsing.vault import VaultSecret

vault = VaultLib([(DEFAULT_VAULT_ID_MATCH, VaultSecret('password'))])
print vault.decrypt(open('/path/to/vault.yml').read())

源代码的数量是相等的,但是包提供了两个Ansible版本的自动yaml解析+处理。

答案 1 :(得分:2)

扩展Kuba的答案,ansible-vault是VaultLib的包装器。它可以很好地处理Vaultlib的Pre Ansible 2.4版本以及2.4版本。

ansible-vault load()方法不仅解密文件,还解析它并将内容作为dict返回。如果你想要内容而不解析,最简单的方法就是用以下内容扩展ansible-vault:

reset

答案 2 :(得分:2)

如果您在ansible.cfg中配置了vault_password_file,则可以按照以下步骤将密码传递给VaultLib

导入:

from ansible import constants as C
from ansible.parsing.vault import VaultLib
from ansible.cli import CLI
from ansible.parsing.dataloader import DataLoader

然后,您可以致电:

loader = DataLoader()
vault_secret = CLI.setup_vault_secrets(
    loader=loader,
    vault_ids=C.DEFAULT_VAULT_IDENTITY_LIST
)
vault = VaultLib(vault_secret)
vault.decrypt(open('/path/to/vault.yml').read())

答案 3 :(得分:1)

你想通过Ansible Python API读取和解密加密文件,对吗?

在Ansible 2.0及以上版本中:

def execute_ansible_command(play_source, stdout_callback):
    from ansible.executor.task_queue_manager import TaskQueueManager
    from ansible.inventory import Inventory
    from ansible.parsing.dataloader import DataLoader
    from ansible.playbook import Play
    from ansible.vars import VariableManager

    Options = namedtuple('Options', ['connection', 'module_path', 'forks', 'remote_user',
                                     'private_key_file', 'ssh_common_args', 'ssh_extra_args', 'sftp_extra_args',
                                     'scp_extra_args', 'become', 'become_method', 'become_user', 'verbosity',
                                     'check'])
    variable_manager = VariableManager()
    loader = DataLoader()
    loader.set_vault_password(ANSIBLE_VAULT_PASS)
    options = Options(connection='smart', module_path=None, forks=100,
                      remote_user=None, private_key_file=None, ssh_common_args="-o StrictHostKeyChecking=no",
                      ssh_extra_args=None, sftp_extra_args=None, scp_extra_args=None, become=None,
                      become_method=None, become_user=None, verbosity=None, check=False)
    passwords = dict()
    inventory = Inventory(loader=loader, variable_manager=variable_manager, host_list=ANSIBLE_INVENTORY)
    variable_manager.set_inventory(inventory)

    play = Play().load(play_source, variable_manager=variable_manager, loader=loader)

    tqm = None
    try:
        tqm = TaskQueueManager(
            inventory=inventory,
            variable_manager=variable_manager,
            loader=loader,
            options=options,
            passwords=passwords,
            stdout_callback=stdout_callback,
        )
        tqm.run(play)
    finally:
        if tqm is not None:
            tqm.cleanup()

DataLoader类用于加载和解析YAML或JSON内容,它具有set_vault_password函数,您可以发送文件库密码来解密文件库加密文件

答案 4 :(得分:1)

如果整个yaml文件都已加密,则
broferek的答案有效。如果您的yaml文件未加密但包含加密的变量,则会抱怨。无论哪种方式都可以工作:

导入:

from ansible import constants as C
from ansible.cli import CLI
from ansible.parsing.vault import VaultLib
from ansible.parsing.dataloader import DataLoader

然后使用DataLoader类将文件读取到字典中

cfgfile = "/path/to/yaml/file.yml"
loader = DataLoader()
vault_secrets = CLI.setup_vault_secrets(loader=loader,
            vault_ids=C.DEFAULT_VAULT_IDENTITY_LIST)
loader.set_vault_secrets(vault_secrets)
data = loader.load_from_file(cfgfile)
pprint.pprint(data)

答案 5 :(得分:1)

我无法使用上述答案进行解密,但是我在这里确实有一个使用子进程并且运行良好的函数:

def vault_decrypt(text, vault_password_file):
    """
    Calls ansible vault and pass the payload via stdin
    :param text: str, text to decode
    :param vault_password_file: str, vault password
    :return: str, decoded text
    """
    cmd = ['ansible-vault', 'decrypt', '--vault-password-file={}'.format(vault_password_file)]
    p = Popen(cmd,
              stdout=PIPE, stdin=PIPE, stderr=PIPE)
    output = p.communicate(input=str.encode(text))
    return output[0].decode("utf-8")

如果我将其更新为直接使用ansible python模块,我将进行更新。干杯。

答案 6 :(得分:0)

这不是我想要的,但通过ansible view <vaultfile>运行subprocess命令,解决了上述问题。

import subprocess
import yaml

def getCreds():
    cmd = "ansible-vault view credentials.vault"
    process = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
    (result, error) = process.communicate()

    resultYaml = yaml.load(result)

    accesskey = resultYaml['accesskey']
    secretkey = resultYaml['secretkey']

    return(accesskey, secretkey)

直接在Python中直接调用Ansible方法仍然是最好的。