Reputation: 95
I have the following list, which I have queried with the help of json_query
from cisco controller.
"aci_access_port_list": [
[
{
"description": [
"NOMON KASTOM"
],
"port_name": "E1-17"
},
{
"description": [
"ASDF NOMON K"
],
"port_name": "E1-16"
},
{
"description": [
"NOMON K9876"
],
"port_name": "E1-15"
},
{
"description": [
"LAN5002 TC "
],
"port_name": "E1-46"
},
{
"description": [
"LAN5002 TC "
],
"port_name": "E1-47"
},
{
"description": [
"NOMON LAN5001 TC "
],
"port_name": "E1-45"
},
{
"description": [
"LAN5001 TC "
],
"port_name": "E1-48"
},
{
"description": [
"NOMON No Cabling - TEST-4-AUTOMATION"
],
"port_name": "E1-30"
},
{
"description": [
"NOMON No Cabling - TEST-6-AUTOMATION"
],
"port_name": "E1-31"
}
]
]
I want to check every description
key and if it has "NOMON K" written save it into a new list. For this I wrote the following:
- set_fact:
clean_list: [\n]
- name: getting the clean list of ports and descr.
set_fact:
clean_list: "{{clean_list }} \n {{item.0.port_name}} - {{item.1}}"
loop: "{{ aci_access_port_list[0]|subelements('description') }}"
when: item.1 is search ("NOMON K")
- debug:
msg: "{{ clean_list }}"
and this returns:
ok: [acitst-apic.net.dsh.at] => {
"msg": "[u'\\\\n'] \n E1-17 - NOMON KASTOM \n E1-16 - ASDF NOMON K \n E1-15 - NOMON K9876"
}
What I want to have is same formatting as aci_access_port_lists
but I couldn't figure it out. It should look like:
"clean_list":[
{
"description": [
"NOMON KASTOM"
],
"port_name": "E1-17"
},
{
"description": [
"ASDF NOMON K"
],
"port_name": "E1-16"
},
{
"description": [
"NOMON K9876"
],
"port_name": "E1-15"
}
]
I assume there is a better way but I couldn't find it and if somebody can help me I will be glad. Thank you in advance.
Upvotes: 2
Views: 118
Reputation: 44615
This is easilly feasible using the selectattr
filter and the contains
test, targeting the first element of the description
list since it always has a single element. Of course, this approach will break if you have several elements in that list.
- name: Show me a clean list
vars:
clean_list: >-
{{
aci_access_port_list.0 |
selectattr('description.0', 'contains', 'NOMON K') |
list
}}
debug:
var: clean_list
Upvotes: 3