Inside my ansible playbook, I' m trying to filter a json result but for now, it doesn't work.
1/ Playbook
Below My ansible playbook to query and filter the result:
tasks:
- name: "Query Attributes"
...
...
register: query_result
- name: Display Result
debug:
var: query_result
- name: Display Filtered Result
debug:
msg: "{{ query_result.current| json_query('[].context.attributes[?name==`prod`].name') }}"
Maybe an issue inside my json_query filter ?
Any idea ?
2/ Query_result output before filtering
TASK [Display Result] ***************************************************
"query_result": {
"ansible_facts": {
"discovered_interpreter_python": "/usr/bin/python"
},
"changed": false,
"current": [
{
"context": {
"attributes": {
"name": "prod",
"uid": "11756"
}
}
},
{
....
}
}
},
{
"context": {
"attributes": {
"name": "dev",
"uid": "14424"
}
}
}
],
"failed": false
}
}
*****************************
3/ Filtered result is empty
Unfortunately my result is empty.
TASK [Display Filtered Result] **********************************************************
{
"msg": []
}
Thank you
Ju
First of all, single and double quotes matter in jmespath expressions specification. Your literal string for the search needs to be single quoted.
Second, your filter will not match. You either have to move your filter at a higher level in the the stream processing or to pipe your expression.
Below are some examples that illustrate the above recommendations and lead to the same result
---
- name: Filter with jmespath
hosts: localhost
gather_facts: false
vars:
query_result: {
"ansible_facts": {
"discovered_interpreter_python": "/usr/bin/python"
},
"changed": false,
"current": [
{
"context": {
"attributes": {
"name": "prod",
"uid": "11756"
}
}
},
{
"context": {
"attributes": {
"name": "dev",
"uid": "14424"
}
}
}
],
"failed": false
}
tasks:
- name: Display original result
debug: var=query_result
- name: Display Filtered Result - One expression - one liner
debug:
msg: "{{ query_result.current | json_query(\"[?context.attributes.name=='prod'].context.attributes.name[]\") }}"
- name: Display Filtered Result - One expression - Query in block var
vars:
query: >-
[?context.attributes.name=='prod'].context.attributes.name[]
debug:
msg: "{{ query_result.current | json_query(query) }}"
- name: Display Filtered Result - Pipe expressions - Query in block var
vars:
query: >-
[].context.attributes[] | [?name=='prod'].name[]
debug:
msg: "{{ query_result.current | json_query(query) }}"
For your next question, please read the help section and consider providing a full MVCE directly in your question (as I just did in this answer).