带有 jinja2 循环的 ansible 剧本

带有 jinja2 循环的 ansible 剧本

我需要使用 jinja2 tamplate 编写一本剧本,以便在 ansible 中编写防火墙规则。为此我写了

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

在模板和

---

- 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

在剧本中。我期望的输出是

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

但结果是

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

那么有人可以帮我解决这个问题吗?

答案1

我建议使用loop而不是模板化剧本。

---
- 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 }}"

相关内容