- Network Automation Cookbook
- Karim Okasha
- 274字
- 2025-04-04 13:10:14
There's more...
In case we need to have more control over the interface configuration, and to set parameters that are not covered by the declarative Ansible modules that we have outlined in this section, we can use Jinja2 templates to achieve this goal. Using the exact same approach that we outlined in the previous recipe for system configuration, we can generate the interface configuration needed for our Juniper devices.
Using the same Ansible role that we have created in the previous recipe, we can extend it to generate the interface configuration for our Juniper devices. We use the following steps in order to accomplish this task:
- Create a new Jinja2 template file called intf.j2 in the templates folder, with the following data:
$ cat roles/build_router_config/templates/junos/intf.j2
interfaces {
{% for intf in p2p_ip[inventory_hostname] | sort(attribute='port') %}
{{ intf.port.split('.')[0] }} {
description "peer:{{intf.peer}} -- peer_port: {{intf.pport}}"
unit 0 {
family inet {
address {{intf.ip}}/{{global.p2p_prefix}};
}
family mpls;
}
}
{% endif %}
{% endfor %}
lo0 {
unit 0 {
family inet {
address {{lo_ip[inventory_hostname]}};
}
}
}
- Update the build_device_config.yml file under the tasks directory with the new task to generate the interface configuration, as follows:
$ cat roles/build_router_config/tasks/build_device_config.yml
<-- Output Trimmed for brevity ------>
- name: "Interface Configuration"
template:
src: "{{Ansible_network_os}}/intf.j2"
dest: "{{build_dir}}/01_intf.cfg"
tags: intf
This is the generated interface configuration for the mxp02 device after running the playbook:
interfaces {
ge-0/0/0 {
description "peer:mxpe01 -- peer_port: ge-0/0/1"
unit 0 {
family inet {
address 10.1.1.8/31;
}
family mpls;
}
}
ge-0/0/1 {
description "peer:mxpe02 -- peer_port: ge-0/0/1"
unit 0 {
family inet {
address 10.1.1.10/31;
}
family mpls;
}
}
<-- Output Trimmed for brevity ------>
lo0 {
unit 0 {
family inet {
address 10.100.1.253/32;
}
}
}