Build a list from multiple hosts in Ansible

Viewed 295

I am trying to build a list of switch serial numbers using Ansible. The serial number is retrieved using IOS Facts and is easy but I cannot get the list no to be incremental, it just overwrites the list with the latest serial.

Here's the partial code I have:

 tasks:

- name: Get all facts from ios devices
  register: all_facts
  ios_facts:
    gather_subset: hardware

- name: Create list Serials
  set_fact:
    IOSserials: "{{ IOSserials + [ all_facts.ansible_facts.ansible_net_serialnum ] }}"

- name: Display list
  debug:
    msg: "The list is: {{ IOSserials }}"

And here's the result I get:

TASK [Create list Serials] *****************************************************
ok: [lab3650s2] => {"ansible_facts": {"IOSserials": ["FDO201XXXXD"]}, "changed": false}
ok: [lab3650s1] => {"ansible_facts": {"IOSserials": ["FDO192XXXXV"]}, "changed": false}
ok: [lab4500s1] => {"ansible_facts": {"IOSserials": ["FOX141XXXXV"]}, "changed": false}

TASK [Display list] ************************************************************

ok: [lab4500s1] => {
"msg": "The list is: ['FOX141XXXXV']"
}
ok: [lab3650s2] => {
"msg": "The list is: ['FDO201XXXXD']"
}
ok: [dev-lab3650s1] => {
"msg": "The list is: ['FDO192XXXXV']"

I'm trying to get a result like:

    ['FOX141XXXXV','FDO201XXXXD','FDO192XXXXV']"
1 Answers

It's possible to map extract. For example

- debug:
    msg: "{{ ansible_play_hosts_all|map('extract', hostvars, 'IOSserials')|list }}"
  run_once: true

gives

    "msg": [
        "FOX141XXXXV", 
        "FDO201XXXXD", 
        "FDO192XXXXV"
    ]
Related