For Part I & Part II of this series.
The goal of this playbook is to be able to generate unique configuration for each switch. In this case, we are configuring a port to work as an access-port for a specific vlan. The port and vlan variable is different for each switch.
config-gen.yml
--- - hosts: 127.0.0.1 connection: local gather_facts: no tasks: - name: GET DATA include_vars: ./host_vars/file.yml - name: GENERATE CONFIG template: src: ./templates/accessvlan.j2 dest: ./config-output/{{ item.switch }}.conf with_items: "{{ file_vlan }}"
file.yml
--- file_vlan: - { switch: switch-1, port: Gi1/8, vlan: 395 } - { switch: switch-1, port: Gi1/23, vlan: 388 } - { switch: switch-2, port: Gi1/8, vlan: 395 } - { switch: switch-2, port: Gi1/23, vlan: 388 } - { switch: switch-3, port: Gi1/9, vlan: 395 } - { switch: switch-3, port: Gi1/24, vlan: 388 } - { switch: switch-4, port: Gi1/9, vlan: 395 } - { switch: switch-4, port: Gi1/24, vlan: 388 }
accessvlan.j2
{% for grouper, host in file_vlan|groupby('switch') %} {% if item.switch == grouper %} {% for item in host %} int {{ item.port }} switchport access vlan {{ item.vlan }} {% endfor %} {% endif %} {% endfor %}
When the “config-gen.yml” playbook is executed:
ansible-playbook config-gen.yml
we get the following output files:
~/ansible_play/config-output$ cat switch-1.conf int Gi1/1 switchport access vlan 195 int Gi1/10 switchport access vlan 188 ~/ansible_play/config-output$ cat switch-2.conf int Gi1/2 switchport access vlan 295 int Gi1/20 switchport access vlan 288 ~/ansible_play/config-output$ cat switch-3.conf int Gi1/3 switchport access vlan 395 int Gi1/30 switchport access vlan 388 ~/ansible_play/config-output$ cat switch-4.conf int Gi1/4 switchport access vlan 495 int Gi1/40 switchport access vlan 488