- Network Automation Cookbook
- Karim Okasha
- 306字
- 2025-04-04 13:10:13
How it works...
First of all, we are using the blockinfile module to create a new configuration file on the Ansible control machine. This module is very similar to the template module. However, we can write the Jinja2 expressions directly in the module in the block option. We define a new variable called interfaces using the vars parameter in the playbook. This variable is a list data structure where each item in the list is a dictionary data structure. This nested data structure specifies the IP prefix used on each interface.
In the Jinja2 expressions, we can see that we have used a number of filters as shown here:
- {{ hostname | upper}}: upper is a Jinja2 filter that transforms all the letters of the input string into uppercase. In this way, we pass the value of the hostname variable to this filter and the output will be the uppercase version of this value.
- {{intf.prefix | ipv4(1) | ipv4('address') }}: Here, we use the Ansible IP address filter twice. ipv4(1) takes an input IP prefix and outputs the first IP address in this prefix. We then use another IP address filter, ipv4('address'), in order to only get the IP address part of an IP prefix. So in our case, we take 10.1.1.0/24 and we output 10.1.1.1 for the first interface.
- {{intf.prefix | ipv4('netmask') }}: Here, we use the Ansible IP address filter to get the netmask of the IP address prefix, so in our case, we get the /24 subnet and transform it to 255.255.255.0.
The output file for the csr1 router after this playbook run is shown here:
$ cat configs/csr1_interfaces.cfg
# BEGIN ANSIBLE MANAGED BLOCK
hostname EDGE-CSR1
!
interface FastEthernet0/0
ip address 10.1.1.1 255.255.255.0
!
!
interface FastEthernet1/0
ip address 10.1.2.1 255.255.255.0
!
# END ANSIBLE MANAGED BLOCK