Ansible Dictionary/Hash 键作为特殊变量

Ansible Dictionary/Hash Key as Special Variable

我正在尝试将一个 Ansible 事实设置为 dict/hash 但我想使用一个特殊变量作为键。在我的例子中,我想使用特殊变量 inventory_hostname。但是,当我尝试这样做时,该值作为字符串而不是主机名机器的实际名称返回。如何将密钥设置为特殊变量 inventory_hosthame

我已经尝试了以下方法,但没有用。

set_fact:

  set_fact:
    result_dict:
      "{{inventory_hostname}}": 'Linux'

  set_fact:
    result_dict:
      inventory_hostname: 'Linux'

我返回的不是实际的 inventory_hostname 字符串值。

当前输出:

    ok: [host-a] => {
    "result_dict": {
        "{{inventory_hostname}}": "Linux"
    }
}

你可以这样写你的任务:

- hosts: localhost
  tasks:
    - set_fact:
        result_dict: "{{ {inventory_hostname: 'Linux'} }}"

    - debug:
        var: result_dict

这似乎对我有用。