簡體   English   中英

Ansible-多個字典文件

[英]Ansible - Multiple Dictionary Files

劇本:

---
- hosts: switch
  connection: local
  gather_facts: no

  tasks:
  - name: GET DATA
    include_vars: ./host_vars/file.yml

  - name: GENERATE CONFIG
    template:
      src: ./templates/accessvlan.j2
      dest: ./output/{{ item.switch }}.conf
    with_items: 
    - '{{ab351E}}'
    - '{{ab361E}}'

變量文件: ./host_vars/file.yml

---
ab351E:
- { switch: ab35-1E, port: Gi1/14, vlan: 1310 }
- { switch: ab35-1E, port: Gi1/29, vlan: 1382 }
- { switch: ab35-1E, port: Gi1/15, vlan: 1310 }

ab361E:
- { switch: ab36-1E, port: Gi1/15, vlan: 1410 }
- { switch: ab36-1E, port: Gi1/26, vlan: 1482 }
- { switch: ab36-1E, port: Gi1/17, vlan: 1410 }

Jinja2模板:/templates/accessvlan.j2

conf t
{% for host in ab351E %}
int {{ host.port }}
switchport access vlan {{ host.vlan }}
{% endfor %}
end
copy run start

我可以使上述劇本正常工作。 然而,作為模板的Jinja2看到了,我可以從只使用一個字典變量(ab351E) with_item

如何編輯Jinja2模板,以便我可以利用劇本with_itemwith_item兩個字典變量(ab351E和ab361E)?

我的目標是生成2個配置文件:ab35-1E.conf和ab36-1E.conf。

ab35-1E.conf文件將如下所示:

conf t
int G1/14
switchport access vlan 1310
int G1/29
switchport access vlan 1382
int G1/15
switchport access vlan 1310
end
copy run start

我認為您可以使用include將項目傳遞給模板,以獲得所需的行為:

conf t
{% for host in item %}
int {{ host.port }}
switchport access vlan {{ host.vlan }}
{% endfor %}
end
copy run start

將此塊移到名為“ generate_config.yml”的文件中

- name: GENERATE CONFIG
  template:
    src: ./templates/accessvlan.j2
    dest: ./output/{{ item.switch }}.conf

在您的劇本中:

- name: generate all configs
  include: generate_config.yml
  with_items:
  . . .

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM