After completing this section, you should be able to:
Run a task that loops over a list of network interfaces.
Obtain a list of network interfaces from a network device.
Reinitialize the layer 3 configuration of a network device.
You saw a previous example in a Guided Exercise of a Jinja2 loop over a defined list of interfaces:
{% for intf in interface_data[inventory_hostname] %}
{% if not intf.name.startswith('Loopback') %}
interface {{ intf.name }}
no shutdown
{% endif %}
{% endfor %}
You can do a similar operation directly within a task using loop:
- name: enable all interaces defined by variable
ios_interface:
enable: True
loop: "{{ interface_data[inventory_hostname] }}"Instead of providing a list of interfaces, you can obtain the list of interfaces from the device and apply an action to each.
Some *os_facts modules set an ansible_net_interfaces variable with a list of interfaces that are configured to exist on devices.
The ios_facts module does this.
If you are working with a platform for which its *os_facts module does not support a documented way of automatically obtaining a list of interfaces, the *os_code module can be used.
The result returned from a command is associated with a variable name by using the register keyword.
If you want a list of interface names, additional processing is necessary.
- name: send command to show interfaces
vyos_command:
commands:
- show interfaces
register: result
- set_fact:
ethernet_interface_rows: "{{ result.stdout_lines[0] | select('search', '^eth[0-9]+.*') | list }}"
- name: append to list
set_fact:
ethernet_interfaces: "{{ ethernet_interfaces }} + [ '{{ item.split(' ')[0] }}' ]"
loop: "{{ ethernet_interface_rows }}"The ability to reinitialize layer 3 on a network device can be extremely useful. It is a powerful, and potentially dangerous, ability.
Removes IPv4 and IPv6 layer 3 addresses.
Removes routing configuration.
Use in testing and training environments to establish a clean baseline.
Might be useful along the side of production environments to process devices returned from the field, or in preparation for provisioning devices.
Care should be taken to prevent accidental use in production.