Network Automation Cookbook
上QQ阅读APP看书,第一时间看更新

There's more...

Using the information that is collected from the ios_facts module, we can generate structured reports for the current state of the network and use these reports in further tasks. In this section, we will outline how to modify our playbook to build this report.

Add a new task to the pb_collect_facts.yml playbook, as shown in the following code:

- name: "P1T2: Write Device Facts"
blockinfile:
path: ./facts.yml
create: yes
block: |
device_facts:
{% for host in play_hosts %}
{% set node = hostvars[host] %}
{{ node.Ansible_net_hostname }}:
serial_number: {{ node.Ansible_net_serialnum }}
ios_version: {{ node.Ansible_net_version }}
{% endfor %}
all_loopbacks:
{% for host in play_hosts %}
{% set node = hostvars[host] %}
{% if node.Ansible_net_interfaces is defined %}
{% if node.Ansible_net_interfaces.Loopback0 is defined %}
- {{ node.Ansible_net_interfaces.Loopback0.ipv4[0].address }}
{% endif %}
{% endif %}
{% endfor %}
run_once: yes
delegate_to: localhost

We use the blockinfile module to build a YAML file called facts.yml. We use Jinja2 expressions within the blockinfile module to customize and select the information we want to capture from the Ansible facts that were captured from the ios_facts task. When we run the pb_collect_facts.yml playbook, we generate the facts.yml file, which has the following data:

device_facts:
wan01:
serial_number: 90L4XVVPL7V
ios_version: 16.06.01
wan02:
serial_number: 9UOFOO7FH19
ios_version: 16.06.01
core01:
serial_number: 67109088
ios_version: 15.1
core02:
serial_number: 67109104
ios_version: 15.1
all_loopbacks:
- 10.100.1.3
- 10.100.1.4
- 10.100.1.1
- 10.100.1.2