'ansible json_query to extract value dependant on other field
Looking to extract href value for each flavor from below json when rel==self and I just can't work it out
{
"flavors": [
{
"id": "1",
"links": [
{
"href": "http://127.0.0.1:8764/v2.1/flavors/1",
"rel": "self"
},
{
"href": "http://127.0.0.1:8764/flavors/1",
"rel": "bookmark"
}
],
"name": "m1.tiny"
},
{
"id": "2",
"links": [
{
"href": "http://127.0.0.1:8764/v2.1/flavors/2",
"rel": "self"
},
{
"href": "http://127.0.0.1:8764/flavors/2",
"rel": "bookmark"
}
],
"name": "m1.small"
},
{
"id": "3",
"links": [
{
"href": "http://127.0.0.1:8764/v2.1/flavors/3",
"rel": "self"
},
{
"href": "http://127.0.0.1:8764/flavors/3",
"rel": "bookmark"
}
],
"name": "m1.medium"
}
]
}
I have tried below but just cant get the jmesquery: 'flavors.links[?contains(rel,
self)]'
query to work?
- name:
uri:
url: 'http://192.168.1.182:8774/v2.1/flavors'
method: GET
body_format: json
headers:
X-Auth-Token: "{{ ansible_facts.auth_token }}"
Content-Type: "application/json; charset=UTF-8"
return_content: yes
register: this
- debug:
msg: "{{ this }}"
- name: save the Json data to a Variable as a Fact
set_fact:
jsondata: "{{ this }}"
- debug:
msg: "{{ jsondata }}"
- name: save the Json data to a Variable as a Fact
set_fact:
flavors: "{{ jsondata | json_query(jmesquery) }}"
vars:
jmesquery: 'json.flavors'
- debug:
msg: "{{ flavors }}"
- name: LINKS
set_fact:
links: "{{ jsondata | json_query(jmesquery) }}"
vars:
jmesquery: 'flavors.links[?contains(rel, `self`)]'
- debug:
msg: "{{ links }}"
I can print the values for all href using below...
- name: save the Json data to a Variable as a Fact
set_fact:
href: "{{ jsondata | json_query(jmesquery) }}"
vars:
jmesquery: 'json.flavors[*].links[].href'
- debug:
msg: "{{ href }}"
Any help appreciated?
Solution 1:[1]
Actually, I have eventually worked it out...
- name: save the Json data to a Variable as a Fact
set_fact:
href: "{{ jsondata | json_query(jmesquery) }}"
vars:
jmesquery: json.flavors[].links[?rel==`self`].href
- debug:
msg: "{{ href }}"
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 |