如何在Python脚本中查看/解密Ansible Vault凭证文件? [英] How to view/decrypt Ansible vault credentials files from within a Python script?

查看:155
本文介绍了如何在Python脚本中查看/解密Ansible Vault凭证文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm trying to figure out how to provide the following facilities to a Python script so that it can:

  1. 导入Ansible Python模块
  2. 打开我定义的ansible.cfg并读取vault_password_file变量
  3. 读取vault_password_file并临时存储在Python变量中
  4. 解密引用的Ansible Vault文件
  1. Import Ansible Python modules
  2. Open up my defined ansible.cfg and read vault_password_file variable
  3. Read vault_password_file and temporarily store in a Python variable
  4. Decrypt a referenced Ansible vaulted file

我通过Google找到了此代码,但没有找到尝试时似乎可以正常工作:

I found this code via google but it did not appear to work when I tried it:

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.

When I investigated this I saw no indications of this function in any Ansible related files, leading me to believe that this method no longer worked with some newer version(s) of Ansible.

最重要的是,我希望有一些方法可以从Python脚本中导入Ansible库/模块,以便可以从Python中以编程方式与ansible-vault托管文件进行交互.

Bottom line is that I'd like some method for importing Ansible libraries/modules from a Python script, so that I can interact with ansible-vault managed files programmatically from Python.

推荐答案

ansible-vault扩展了Kuba的答案,是VaultLib的包装.它很好地处理了Vaultlib的Ansible 2.4之前版本以及2.4的后版本.

Extending Kuba's answer, ansible-vault is a wrapper around VaultLib. It nicely handles the pre Ansible 2.4 version of Vaultlib along with the post 2.4 version.

ansible-vault load()方法不仅解密文件,还解析文件并将内容作为dict返回.如果您希望内容不进行解析,则最简单的方法是使用以下内容扩展ansible-vault:

The ansible-vault load() method not only decrypts the file, but it also parses it and returns the contents as a dict. If you want the contents without parsing, it is probably easiest to just extend ansible-vault with something like:

from ansible_vault import Vault

class MyVault(Vault):
    def load_raw(self, stream):
        return self.vault.decrypt(stream)

    def dump_raw(self, text, stream=None):
        encrypted = self.vault.encrypt(text)
        if stream:
            stream.write(encrypted)
        else:
            return encrypted

这篇关于如何在Python脚本中查看/解密Ansible Vault凭证文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆