如何在ansible中遍历库存组?

时间:2019-01-07 18:59:03

标签: ansible

我看过一些与我的问题类似的SO帖子:Ansible : iterate over inventory groupsAnsible iterate over hosts in inventory group set by variable和其他帖子,但我仍然不明白我在做什么错:

这是我的库存文件:

[root@82c420275711 playbooks]# cat inventory.dev
#
#   - Comments begin with the '#' character
#   - Blank lines are ignored
#   - Groups of hosts are delimited by [header] elements
#   - You can enter hostnames or ip addresses
#   - A hostname/ip can be a member of multiple groups
[localhost]
127.0.0.1

[virtual_centers]
172.17.0.2
172.17.0.5

这是我的剧本中出现问题的部分:

- name: "allow {{ item }} to allow port 514"
  firewalld:
    immediate: yes
    rich_rule: "rule family=\"ipv4\" source address=\"{{ item }}\" port protocol=\"udp\" port=\"514\" accept"
    permanent: yes
    state: enabled
  with_items: groups['virtual_centers']

这是我使用清单文件运行剧本时收到的错误消息:

[root@82c420275711 playbooks]# ansible-playbook -i inventory.dev ./configure_syslog-ng_server.yaml
...
    TASK [allow {{ item }} to allow port 514] *******************************************************************************************************************************************************************************************
failed: [127.0.0.1] (item=groups['virtual_centers']) => {"changed": false, "item": "groups['virtual_centers']", "msg": "ERROR: Exception caught: INVALID_ADDR: groups['virtual_centers']"}

我在这里做错了什么?谢谢

1 个答案:

答案 0 :(得分:0)

好,我知道了。我需要这样写任务:

- name: allow {{ item }} to allow port 514
  firewalld:
    immediate: yes
    rich_rule: "rule family=\"ipv4\" source address=\"{{ item }}\" port protocol=\"udp\" port=\"514\" accept"
    permanent: yes
    state: enabled
  with_items:
    - "{{ groups['virtual_centers'] }}"