2016-12-16 34 views
0

劇本:Ansible - 多個字典文件

--- 
- 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模板所示,我只能使用with_item中的一個字典變量(ab351E)。

如何編輯我的Jinja2模板,以便我可以利用在with_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 

回答

0

我認爲你可以使用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: 
    . . .