So here is my current playbook
---
- hosts: SWITCHES
gather_facts: no
tasks:
- name: Show Interface Status
ios_command:
commands:
- show int status
register: out
- debug: var=out.stdout_lines
I basically want to take this script, and then disable all the ports in the "notconnect" state, meaning all the ports with nothing connected to them. Is there a way I can add a "when" statement to this, so that when "show interface status" comes back, it looks at all the ports that are not connected and disables them by applying the "shutdown" command to each interface? I think a "when" statement is what I am needing to do, but not sure where to get started with it. Or is there a better way to accomplish this?
Is there a python script that could accomplish this as well?
You should use ios_facts to retrieve a dictionary containing all the interfaces. Then you can iterate over that dictionary to shutdown the interfaces that are not connected.
If you run your playbook using the -vvv switch, you will see the all the variables collected by ios_facts.
I believe in Ansible 2.9 and later, Ansible gathers the actual network device facts if you specify "gather_facts: yes". With Ansible 2.8 or older, you need to use the "ios_facts" module.
Here is an example from part of a collected "ansible_net_interfaces" variable:
The value of the
"ansible_net_interfaces"
variable is a dictionary. Each key in that dictionary is the interface name, and the value is a new dictionary containing new key/value pairs. The"operstatus"
key will have a value"down"
when the interface is not connected.Using
"with_dict"
in the"ios_config"
task loops through all top-level key/value pairs in the dictionary, and you can use the variables in each key/value pair by referring to"{{ item.key }}"
or "{{ item.value }}"
.Using
"when"
in the"ios_config"
task, you set a condition for when the task is to be executed. In this case we only want it to run when"operstatus"
has a value of"down"
.The
"parents"
parameter in the"ios_config"
task specifies a new section where the configuration is to be entered, in this case the section is the interface configuration mode. The interface name is returned for each interface in the"ansible_net_interfaces"
using the"{{ item.key }}"
variable.Refer to Ansibles documentation for these modules to get a better understanding of them: https://docs.ansible.com/ansible/latest/collections/cisco/ios/ios_facts_module.html https://docs.ansible.com/ansible/latest/collections/cisco/ios/ios_config_module.html