[英]PyYAML ConstructError: could not determine a constructor for the tag
[英]PyYAML error: Could not determine a constructor for the tag '!vault'
我正在嘗試讀取包含標簽!vault
的 YAML 文件。 我收到錯誤:
無法確定標簽“!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)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.