gpt4 book ai didi

python - PyYAML 错误 : Could not determine a constructor for the tag '!vault'

转载 作者:行者123 更新时间:2023-12-05 04:42:31 26 4
gpt4 key购买 nike

我正在尝试读取其中包含标签 !vault 的 YAML 文件。我收到错误:

could not determine a constructor for the tag '!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)

关于python - PyYAML 错误 : Could not determine a constructor for the tag '!vault' ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69817464/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com