Ansible,在剧本中使用可变内容时出现问题

Ansible, Issue while using variable content in playbook

我需要在另一台主机上使用为某些主机(在清单中)定义的变量。

这里我在我的库存中定义它

[mygroup:vars]
service_url=my_front_url

其中 mygroup 包含其他组,包含我的主机。

然后是我的剧本:

- name: Get variable
  hosts: 127.0.0.1
  tasks:
  - debug:
      var: hostvars[groups['{{ platform }}'][0]]['service_url']
  - debug:
      msg: "{{ hostvars[groups['\"{{ platform }}\"'][0]]['service_url'] }}"

其中 platform 是一个 extra-var(设置要使用的 "mygroup") 其中 127.0.0.1 是我的 ansible 主机,与我的目标主机不同。

例如:

ansible-playbook test.yaml --extra-vars='platform=my-group' 


    TASK [debug] ********************************************************************************************************************************************************************
    ok: [127.0.0.1] => {
        "hostvars[groups['idi_se_prod'][0]]['service_url']": "my-front-url"
    }

    TASK [debug] ********************************************************************************************************************************************************************
    fatal: [127.0.0.1]: FAILED! => {"msg": "The task includes an option with an undefined variable. The error was: 'dict object' has no attribute '\"{{ platform }}\"'\n\nThe error appears to have been in 'XXXX/ansible/test.yaml': line 6, column 5, but may\nbe elsewhere in the file depending on the exact syntax problem.\n\nThe offending line appears to be:\n\n      var: hostvars[groups['{{ platform }}'][0]]['service_url']\n  - debug:\n    ^ here\n"}

如果我在 yaml 中设置静态组名,这个工作正常。

- name: Get variable
  hosts: 127.0.0.1
  tasks:
  - debug:
      var: hostvars[groups['{{ platform }}'][0]]['service_url']
  - debug:
      msg: "{{ hostvars[groups['mygroup'][0]]['service_url'] }}"


TASK [debug] ********************************************************************************************************************************************************************
ok: [127.0.0.1] => {
    "hostvars[groups['my-group'][0]]['service_url']": "my-front-url"
}

TASK [debug] ********************************************************************************************************************************************************************
ok: [127.0.0.1] => {
    "msg": "my_front_url"
}

它看起来像是一个语法问题,但我尝试了很多方法,我认为我可以使用一些帮助。

谢谢

尼古拉斯

{{}} 中的所有内容或多或少只是 python,所以不要像你这样使用递归模板:

  msg: "{{ hostvars[groups['\"{{ platform }}\"'][0]]['service_url'] }}"

而是直接引用变量,一个变量:

  msg: "{{ hostvars[groups[platform][0]]['service_url'] }}"