Search code examples
pythonansiblecisco

Ansible. Determine most popular value in array


 tasks:

   - name: Find popular vlan
     ios_command:
       provider: "{{ cli }}"
       commands:
         - show run | i switchport access vlan
     register: sh_res

   - debug: var=sh_res

Debug sh_res is look like this:

  "stdout_lines": [
            [
                "switchport access vlan 40", 
                " switchport access vlan 22", 
                " switchport access vlan 22", 
                " switchport access vlan 22", 
                " switchport access vlan 22", 
                " switchport access vlan 22", 
                " switchport access vlan 22", 
                " switchport access vlan 22", 
                " switchport access vlan 22", 
                " switchport access vlan 30", 
                " switchport access vlan 20", 
                " switchport access vlan 22", 
                " switchport access vlan 22", 
                " switchport access vlan 22", 
                " switchport access vlan 22", 
                " switchport access vlan 22", 
                " switchport access vlan 22", 
                " switchport access vlan 22", 
                " switchport access vlan 22"
            ]
        ]
    }
}

I need to determine most popular vlan on the switch and put in into variable {{vlan}}. In this case it is 22. How can I do that?


Solution

  • Firstly, you should reach all of vlan:

    stdout_lines = sh_res['stdout_lines'][0]
    vlans = [line.split()[-1] for line in stdout_lines] #['40', '22', ..., '22', '22']
    

    After that you just need to find most frequent item in vlans. Check this topic. Counter from collections can be used to find most frequent item.

    from collections import Counter
    
    vlanCounter = Counter(vlans)
    print(vlanCounter.most_common(1)) #[('22', 16)]
    print(vlanCounter.most_common(1)[0][0]) #'22'