How to iterate over inventory group in ansible?

2019-08-24 03:50发布

I have looked at some of the SO post that are similar to my question: Ansible : iterate over inventory groups, Ansible iterate over hosts in inventory group set by variable and others but I still don't understand what I am doing wrong:

Here is my inventory file:

[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

Here is the part of my playbook that is having trouble:

- 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']

Here is the error message I get when I run the playbook with that inventory file:

[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']"}

What am I doing wrong here? thanks

标签: ansible
1条回答
Evening l夕情丶
2楼-- · 2019-08-24 04:27

ok I figured it out. I needed to write that task like so:

- 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'] }}"
查看更多
登录 后发表回答