0

I need to write a playbook using jinja2 tamplate inorder to write firewalld rule in ansible. For that I wrote

---
- name: Firewalld check
  hosts: localhost
  become: yes

  tasks:
  - name: Allow ICMP traffic
    firewalld:
      rich_rule: rule family='ipv4' source address=" {{ source }} " protocol value="icmp" accept
      permanent: no
      state: enabled

in template and

---

- name: Firewalld config
  hosts: localhost
  become: yes

  vars:
    source:
       - 172.16.2.114
       - 172.16.2.115
  tasks:

  - name: Rules
    template:
      src: playtem.yml.j2
      dest: playbook.yml

in playbook. The output I expected is

---
- name: Firewalld check
  hosts: localhost
  become: yes

  tasks:
  - name: Allow ICMP traffic
    firewalld:
      rich_rule: rule family='ipv4' source address="172.16.2.114" protocol value="icmp" accept
      permanent: no
      state: enabled
  - name: Allow ICMP traffic
    firewalld:
      rich_rule: rule family='ipv4' source address="172.16.2.115" protocol value="icmp" accept
      permanent: no
      state: enabled

but the outcome which came is

---
- name: Firewalld check
  hosts: localhost
  become: yes

  tasks:
  - name: Allow ICMP traffic
    firewalld:
      rich_rule: rule family='ipv4' source address=" [u'172.16.2.114', u'172.16.2.115'] " protocol value="icmp" accept
      permanent: no
      state: enabled

So could anyone help me to solve this problem please?

0

1 Answer 1

2

I'd suggest using loop instead of templating out a playbook.

---
- name: Firewalld check
  hosts: localhost
  become: yes
  vars:
    source:
       - 172.16.2.114
       - 172.16.2.115
  tasks:
    - name: Allow ICMP traffic
      firewalld:
        rich_rule: rule family='ipv4' source address="{{ item }}" protocol value="icmp" accept
        permanent: no
        state: enabled
      loop: "{{ source }}"
2
  • Thank you. Your answer was helful. But when using many varibles and many modules in a playbook, which method will you recommend? Commented Jul 8, 2020 at 13:25
  • You should give this a good read: docs.ansible.com/ansible/latest/user_guide/… It's hard to say what works best for you - highly dependant on use case and infrastructure Commented Jul 8, 2020 at 15:34

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.