Gathering and Using Data from Cisco NX-OS with Ansible Modules

easy button

Reliably executing repetitive tasks with automation is easy (after the work is done)

Given enough work, self-built automation can be easy to consume. Non-consumers (engineers) need to focus on reliability and repeatability, but occasionally there's an opportunity to save time and simplify lives directly.

Information gathering with Ansible is a powerful tool, making the level of difficulty to perform a check on one network node roughly equal to the effort on 2, or even one hundred. Here's a quick and easy way to get started.

Ansible Inventory

Ansible likes to know where each managed node lives, and provides the inventory capability to organize similar devices for remote management. Not all network automation endpoints use the inventory feature, so ensure that you read the published documentation first.

Note: The easiest way to check inventory dependency is to verify if there are directives in the playbook named hostname, username, or password. If they exist, that module probably does not use inventory.

Ansible supports two formats for an on-controller inventory, conf (Windows-like) and YAML (Linux-like). Here's an example in YAML, I personally find it easier to read:

 1---  
 2  nxos_example_001:  
 3    hosts:  
 4      nexus_1:  
 5        ansible_host: "1.1.1.1"  
 6      nexus_2:  
 7        ansible_host: "2.2.2.2"  
 8      vars:  
 9        ansible_user: "admin"  
10  nxos_all:  
11    children:  
12      nxos_example_001:  

We have a little bit to unpack here:

  • The first hierarchical tier is for groups, which can contain other groups if you use the children: directive (see nxos_all as an example)
  • vars: will specify variables to commonly use across all members of that group
  • ansible_host is used to specify an address - and is useful with dual stack environments (or ones that don't have DNS)

Ansible Facts

Ansible stores all of its runtime variables for a given playbook as facts. This is held as a Python dict at runtime by Ansible Engine, and the debug: module allows an engineer to print the output to stdout:

 1---  
 2- hosts: localhost  
 3  connection: local  
 4  tasks:  
 5    - name: "Print it!"  
 6      debug:  
 7        var: lookup('ansible.builtin.env', 'PATH')  
 8    - name: "Print it, but with msg!"  
 9      debug:  
10        msg:  
11          - "The system environment PATH is: {{ lookup('ansible.builtin.env', 'PATH') }}"  
12          - "Wise engineers don't use this feature to print passwords"  

Running this playbook will produce the following:

 1ansible-playbook debug.yml   
 2[WARNING]: No inventory was parsed, only implicit localhost is available  
 3[WARNING]: provided hosts list is empty, only localhost is available. Note that the implicit localhost does not match 'all'  
 4  
 5PLAY [localhost] *************************************************************************************************************************************************************************************************************************************************************************  
 6  
 7TASK [Gathering Facts] *******************************************************************************************************************************************************************************************************************************************************************  
 8ok: [localhost]  
 9  
10TASK [Print it!] *************************************************************************************************************************************************************************************************************************************************************************  
11ok: [localhost] => {  
12    "lookup('ansible.builtin.env', 'PATH')": "/root/.vscode-server/bin/d045a5eda657f4d7b676dedbfa7aab8207f8a075/bin/remote-cli:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin"  
13}  
14  
15TASK [Print it, but with msg!] ***********************************************************************************************************************************************************************************************************************************************************  
16ok: [localhost] => {  
17    "msg": [  
18        "The system environment PATH is: /root/.vscode-server/bin/d045a5eda657f4d7b676dedbfa7aab8207f8a075/bin/remote-cli:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin",  
19        "Wise engineers don't use this feature to print passwords"  
20    ]  
21}  
22  
23PLAY RECAP *******************************************************************************************************************************************************************************************************************************************************************************  
24localhost                  : ok=3    changed=0    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0 

msg: is effective for formatted output, while var: is considerably simpler when dumping a large dictionary. var: does not require Jinja formatting, which may cause playbooks to be simpler.

Let's apply this to a Cisco NX-OS Node. We can register command output from the nxos_facts module.

Note: The example provided below is the "new way", where Network modules follow the Ansible rules. If using older versions of Ansible (Ansible 2), the following may not be fully available!

First, we need to update the Ansible inventory. We will be using the API method to collect data, and it requires multiple new variables:

  • ansible_network_os: Instructs Ansible on what module to use for that system
  • ansible_connection: Instructs Ansible on what transport to use (HTTP API, SSH)
  • ansible_httpapi_use_ssl: Instructs Ansible to use HTTPS
 1---  
 2  nxos_example_001:  
 3    hosts:  
 4      nexus_1:  
 5        ansible_host: "1.1.1.1"  
 6      nexus_2:  
 7        ansible_host: "2.2.2.2"  
 8      vars:  
 9        ansible_user: "admin"  
10        ansible_network_os: 'cisco.nxos.nxos'  
11        ansible_connection: ansible.netcommon.httpapi  
12        ansible_httpapi_password: ''  
13        ansible_httpapi_use_ssl: 'yes'  
14        ansible_httpapi_validate_certs: 'no'  
15  nxos_all:  
16    children:  
17      nxos_example_001:

The updated inventory allows us to run extremely simple playbooks to gather data

 1---  
 2- hosts: nxos_machines  
 3  tasks:  
 4    - name: "Gather facts via NXAPI"  
 5      cisco.nxos.nxos_facts:  
 6        gather_subset: 'min'  
 7        gather_network_resources:  
 8          - 'interfaces'  
 9      register: nxos_facts_gathered  
10    - name: "Print it!"  
11      debug:  
12        var: nxos_facts_gathered  
 1ansible-playbook debug_nxos_facts.yml   
 2  
 3PLAY [nxos_machines] *************************************************************************************************************************************************************************************************************************************************************************************************  
 4  
 5TASK [Gathering Facts] ***********************************************************************************************************************************************************************************************************************************************************************************************  
 6[WARNING]: Ignoring timeout(10) for cisco.nxos.nxos_facts  
 7ok: [nx-1]  
 8  
 9TASK [Gather facts via NXAPI] ****************************************************************************************************************************************************************************************************************************************************************************************  
10ok: [nx-1]  
11  
12TASK [Print it!] *****************************************************************************************************************************************************************************************************************************************************************************************************  
13ok: [nx-1] => {  
14    "nxos_facts_gathered": {  
15        "ansible_facts": {  
16            "ansible_net_api": "nxapi",  
17            "ansible_net_gather_network_resources": [  
18                "interfaces"  
19            ],  
20            "ansible_net_gather_subset": [  
21                "default"  
22            ],  
23            "ansible_net_hostname": "AnsLabN9k-1",  
24            "ansible_net_image": "bootflash:///nxos.9.3.8.bin",  
25            "ansible_net_license_hostid": "",  
26            "ansible_net_model": "Nexus9000 C9300v",  
27            "ansible_net_platform": "N9K-C9300v",  
28            "ansible_net_python_version": "3.9.2",  
29            "ansible_net_serialnum": "",  
30            "ansible_net_system": "nxos",  
31            "ansible_net_version": "9.3(8)",  
32            "ansible_network_resources": {  
33                "interfaces": [  
34                    {  
35                        "name": "Ethernet1/1"  
36                    },  
37                    {  
38                        "name": "mgmt0"  
39                    }  
40                ]  
41            }  
42        },  
43        "changed": false,  
44        "failed": false  
45    }  
46}  
47  
48PLAY RECAP ***********************************************************************************************************************************************************************************************************************************************************************************************************  
49nx-1                       : ok=3    changed=0    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0 

Ansible's Inventory feature enables us to scale per node without any additional code - the previous playbook will execute once on every inventory object in the group, which allows an engineer to thoroughly test a playbook on lab resources with some level of separation.

Deliberate automation design will bear fruit here - as safety is key when developing and testing automation. Like with previous automation-centric posts, thorough, comprehensive testing of automation for reliability is a social responsibility when creating tools.

Establishing a separate CI/CD tooling set to target a lab (or CML, as in this case!) enables us to add additional safeguards against accidental changes, such as ACLs/Firewall policies preventing access from Test CI/CD -> Production network assets. Tools like CML take it even further by allowing an engineer to spin up amnesic NOS instances to run code against.

Here's an applicable instance. Recently, Cisco disclosed a vulnerability with Cisco Fabric Services - and most environments don't need that service running. This is an aggressive fix - but with Ansible we can check for the service and disable it only if it's running, and then check again afterwards. This illustrates the value of idempotency, or the practice of running repeated executions safely.