将字典变量传递给自定义模块

Naf*_*Kay 1 python ansible

我维护了一个用 Python 编写的 Ansible 自定义模块,并且我需要能够将所有检测到的 Ansible 事实作为字典传递到该模块中。

目前,我正在尝试这样做:

- name: run tests
  degoss:
    # ...
    facts: "{{ ansible_facts }}"
Run Code Online (Sandbox Code Playgroud)

我的模块的参数规范如下所示:

AnsibleModule(argument_spec=dict(
  # ...
  facts=dict(required=False, default={}),
), ...)
Run Code Online (Sandbox Code Playgroud)

我的模块文档也指定了这一点:

DOCUMENTATION="""
# ...
options:
  facts:
    required: false
    default: empty dictionary
    description: A dictionary of Ansible facts.
"""
Run Code Online (Sandbox Code Playgroud)

但是,当我进行输入清理和验证时,我收到的是str字典而不是字典:

if not isinstance(self.facts, dict):
    self.fail("The 'facts' parameter to this module must be a dictionary, not a {}".format(type(self.facts)))
Run Code Online (Sandbox Code Playgroud)

这是在运行时抛出的:

The 'facts' parameter to this module must be a dictionary, not a <type 'str'>
Run Code Online (Sandbox Code Playgroud)

我是否需要使用特定语法来将值作为字典传递,或者我是否需要将字典变量视为 JSON 并尝试反序列化它们?

fra*_*aff 5

如此处所述,您可以指定 ansible 可以期望的类型。

AnsibleModule(argument_spec=dict(
  # ...
  facts=dict(required=False, default={}, type=dict),
), ...)
Run Code Online (Sandbox Code Playgroud)

那么“事实”将是一本字典