【问题标题】:PyYAML error: Could not determine a constructor for the tag '!vault'PyYAML 错误:无法确定标签“!vault”的构造函数
【发布时间】:2021-12-17 09:31:14
【问题描述】:

我正在尝试读取包含标签 !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

【问题讨论】:

标签: python yaml pyyaml ansible-vault


【解决方案1】:

要么使用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)

【讨论】:

  • 我可以知道要为 ansible.parsing.yaml.objects 安装哪个包吗?我收到一条错误消息:No module named ansible.parsing.yaml.objects
  • pip install ansible。根据您打算如何使用!vault,您还可以实例化您自己的类。
  • 我已经通过 pip 安装了 ansible,知道这里缺少什么。我正在使用通过 pip pip list 安装 Ansible 的同一用户运行脚本 | grep ansible ansible 2.8.17
  • 您是否使用与 pip list 相同的终端运行脚本?
猜你喜欢
  • 2019-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-11-30
  • 1970-01-01
  • 2017-07-02
  • 2021-06-11
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多