python - PyYAML 错误:无法确定标签“!vault”的构造函数
问题描述
我正在尝试读取包含标签的 YAML 文件!vault
。我得到错误:
无法确定标签“!vault”的构造函数
在阅读了几篇博客后,我了解到我需要指定一些构造函数来解决这个问题,但我不清楚如何去做。
import yaml
from yaml.loader import SafeLoader
with open('test.yml' ) as stream:
try:
inventory_info = yaml.safe_load(stream)
except yaml.YAMLError as exc:
print(exc)
User = inventory_info['all']['children']['linux']['vars']['user']
key = inventory_info['all']['children']['linux']['vars']['key_file']
我正在使用的 YAML 文件:
all:
children:
rhel:
hosts: 172.18.144.98
centos:
hosts: 172.18.144.98
linux:
children:
rhel:
centos:
vars:
user: "o9ansibleuser"
key_file: "test.pem"
ansible_password: !vault |
$ANSIBLE_VAULT;2.1;AES256
3234567899353936376166353
解决方案
要么使用from_yaml
效用函数:
from ansible.parsing.utils.yaml import from_yaml
# inventory_info = yaml.safe_load(stream) # Change this
inventory_info = from_yaml(stream) # to this
或将构造函数添加到yaml.SafeLoader
:
from ansible.parsing.yaml.objects import AnsibleVaultEncryptedUnicode
def construct_vault_encrypted_unicode(loader, node):
value = loader.construct_scalar(node)
return AnsibleVaultEncryptedUnicode(value)
yaml.SafeLoader.add_constructor(u'!vault', construct_vault_encrypted_unicode)
inventory_info = yaml.safe_load(stream)
推荐阅读
- angular - 从 API 获取图像
- html - 如何访问在 html 文件中多次存在的部分中的文本?
- amazon-web-services - 将消息从 lambda 发送到 DLQ 时出错
- salesforce - 如何仅使用 SOQL 更新列中的空值?
- python - TensorFlow 展示模型总结
- prolog - 使用 prolog 为算术表达式创建术语的一阶逻辑
- python - `=` 后面的值在requrements.txt 文件中指定什么?
- c++ - Clion 中关于使用协程的无效错误
- java - 经过长时间的尝试,无法在水平和垂直的回收站视图内的 2 个卡片视图元素之间提供空间
- nginx - 如何通过 kubernetes nginx 中的端口将流量路由到外部 SFTP 服务器?