如何在 Ansible 中使用我的自定义 yaml 标签?

问题描述 投票:0回答:2

我在 Python 中创建了一个 YAML 解析器,以使用 yaml 标签解密值。

password: !decrypt LS0tLS1CRUdJ...TiBQRS0tCg==

在我的解析器脚本中,我可以添加自定义构造函数来解密值。

def get_loader():
  loader = yaml.SafeLoader
  loader.add_constructor("!decrypt", decrypt_constructor)
  return loader

data = yaml.load(open(file, "rb"), Loader=get_loader())

使用 Ansible 解析 YAML 文件时,出现以下错误:

ERROR! We were unable to read either as JSON nor YAML, these are the errors we got from each:
JSON: Expecting value: line 1 column 1 (char 0)

Syntax Error while loading YAML.
  could not determine a constructor for the tag '!decrypt'

如何向 Ansible 使用的 YAML 解析器添加构造函数?我以前见过这些标签,例如

!vault
!unsafe

python ansible yaml
2个回答
1
投票

您需要向 Ansible 添加代码来教它如何解析您的自定义 YAML 标签。

看起来这类东西存在于 Ansible 存储库中的 lib/ansible/parsing/yaml 中。例如,您可以在

!vault
:
 中找到对 
objects.py

对象的支持
class AnsibleVaultEncryptedUnicode(Sequence, AnsibleBaseYAMLObject):
    '''Unicode like object that is not evaluated (decrypted) until it needs to be'''
    __UNSAFE__ = True
    __ENCRYPTED__ = True
    yaml_tag = u'!vault'

[...]

您最终将维护自己的自定义版本的 Ansible。


0
投票

Ansible 使用自己的加载器。需要将标签添加到该加载程序。

add_constructor
是一个类方法。

from ansible.parsing.yaml.loader import AnsibleLoader

AnsibleLoader.add_constructor("!decrypt", decrypt_constructor)

这与ansible==9.3.0,ansible-core==2.16.4。

要设置加载器进行解析,您可以使用插件。该插件需要在读取库存之前加载。也许一个 inventory 插件 就可以了,如果它被 命名为按名称排序 在具有标签的 yaml inventory 之前。

© www.soinside.com 2019 - 2024. All rights reserved.