可靠的。确定数组中最受欢迎的值
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
调试 sh_res 看起来像这样:
"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"
]
]
}
}
我需要确定交换机上最流行的 vlan 并将其放入变量 {{vlan}} 中。在本例中为 22。
我该怎么做?
首先,你应该到达所有的vlan:
stdout_lines = sh_res['stdout_lines'][0]
vlans = [line.split()[-1] for line in stdout_lines] #['40', '22', ..., '22', '22']
之后你只需要在vlans中找到最频繁的项目。 Check this topic. 集合中的计数器可用于查找最常出现的项目。
from collections import Counter
vlanCounter = Counter(vlans)
print(vlanCounter.most_common(1)) #[('22', 16)]
print(vlanCounter.most_common(1)[0][0]) #'22'
tasks:
- name: Find popular vlan
ios_command:
provider: "{{ cli }}"
commands:
- show run | i switchport access vlan
register: sh_res
- debug: var=sh_res
调试 sh_res 看起来像这样:
"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"
]
]
}
}
我需要确定交换机上最流行的 vlan 并将其放入变量 {{vlan}} 中。在本例中为 22。 我该怎么做?
首先,你应该到达所有的vlan:
stdout_lines = sh_res['stdout_lines'][0]
vlans = [line.split()[-1] for line in stdout_lines] #['40', '22', ..., '22', '22']
之后你只需要在vlans中找到最频繁的项目。 Check this topic. 集合中的计数器可用于查找最常出现的项目。
from collections import Counter
vlanCounter = Counter(vlans)
print(vlanCounter.most_common(1)) #[('22', 16)]
print(vlanCounter.most_common(1)[0][0]) #'22'