Python

帶有 jinja2 循環的 ansible 劇本

  • July 8, 2020

我需要使用 jinja2 模板編寫劇本,以便在 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

那麼有人可以幫我解決這個問題嗎?

我建議使用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 }}"

引用自:https://unix.stackexchange.com/questions/597352