
How it works...
We created the network.yml file in order to group all the variables that will apply to all devices under this group. After that, we create two Jinja2 files, one for Cisco IOS devices, and the other for Juniper devices. Inside each Jinja2 template, we reference the Ansible variables using {{}}. We also use the for loop construct, {% for server in ntp_servers %} , supported by the Jinja2 templating engine in order to loop over the ntp_servers variable (which is a list) to access each item within this list.
Ansible provides the template module that takes two parameters:
- src: This references the Jinja2 template file.
- dest: This specifies the output file that will be generated.
In our case, we use the {{inventory_hostname}} variable in order to make the output configuration file unique for each router in our inventory.
By default, the template modules create the output file on the remotely managed nodes. However, this is not possible in our case since the managed devices are network nodes. Consequently, we use the delegate_to: localhost option in order to run this task locally on the Ansible control machine.
The first play in the playbook creates the configs directory to store the configuration files for the network devices. The second play runs the template module on Cisco devices, and the third play runs the template task on Juniper devices.
The following is the configuration file for one of the Cisco devices:
$ cat configs/csr1.cfg
hostname edge-csr1
!
ntp 172.20.1.1
ntp 172.20.2.1
!
This is the configuration file for one of the Juniper devices:
$ cat configs/mx1.cfg
set system host-name core-mx1
set system ntp server 172.20.1.1
set system ntp server 172.20.2.1