问题描述
我试图弄清楚如何为Python脚本提供以下功能,以便它可以:
I'm trying to figure out how to provide the following facilities to a Python script so that it can:
- 导入Ansible Python模块
- 打开我定义的
ansible.cfg
并读取vault_password_file
变量 - 读取
vault_password_file
并临时存储在Python变量中 - 解密引用的Ansible Vault文件
- Import Ansible Python modules
- Open up my defined
ansible.cfg
and readvault_password_file
variable - Read
vault_password_file
and temporarily store in a Python variable - 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凭证文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!