I'm having issues using json_query
to filter arrays that have a certain key value.
This is what shows as the API result when given the direct path to it.
ok: [localhost] => {
"msg": [
{
"accelerated_failback": false,
"action": "sync",
"allow_copy_fb": false,
"bandwidth_reservation": null,
"changelist": false,
"check_integrity": true,
"cloud_deep_copy": "deny",
"conflicted": false,
"database_mirrored": false,
"delete_quotas": true,
"description": "",
"disable_file_split": false,
"disable_fofb": false,
"disable_quota_tmp_dir": false,
"disable_stf": false,
"enable_hash_tmpdir": false,
"enabled": false,
"encrypted": false,
},
{
"accelerated_failback": false,
"action": "sync",
"allow_copy_fb": false,
etc ...........
The key value that I'm trying to filter is enabled: true
which there are a few arrays that have that key value from the result.
How I am querying is with this example:
- name: Gain Eligible Policies {{ item.name }}
ansible.builtin.uri:
url: 'https://{{ item.endpoint_host }}:{{ item.endpoint_port | default(8080) }}/platform/7/sync/policies'
user: '{{ item.endpoint_user }}'
password: '{{ item.endpoint_password }}'
validate_certs: '{{ item.verify_ssl | default(false) }}'
force_basic_auth: true
timeout: '{{ uri_timeout | default(30) }}'
retries: '{{ uri_retries | default(3) }}'
delay: '{{ uri_delay | default(10) }}'
register: api_result
loop: "{{ array_lookup_list }}"
when: item.name not in ignore_clusters_list
- name: API output
debug:
msg: "{{ api_result.results.0.json.policies | json_query( policies ) }}"
vars:
policies: "[?enabled == 'true']"
And only shows this result:
ok: [localhost] => {
"msg": []
}
WHAT I'VE TRIED
I've tried shortening the path to just the variable when showing the API output but it gives me an error of:
- name: API output
debug:
msg: "{{ api_result | json_query( *.policies[\"[?enabled == 'true']\"] ) }}"
result _______________________________
"fatal: [localhost]: FAILED! => {"msg": "template error while templating string: unexpected '.'. String: {{ api_result | json_query( *.policies[\"[?enabled == 'true']\"] ) }}"}"
The value of the attribute enabled is boolean. Simply test it
policies: '[?enabled]'
Example of a complete playbook for testing
- hosts: all
vars:
api_result:
results:
- json:
policies:
- {rec: 1, enabled: false, encrypted: false}
- {rec: 2, enabled: true, encrypted: false}
- {rec: 3, enabled: true, encrypted: false}
tasks:
- debug:
msg: "{{ api_result.results.0.json.policies|json_query(policies) }}"
vars:
policies: '[?enabled]'
gives (abridged)
msg:
- enabled: true
encrypted: false
rec: 2
- enabled: true
encrypted: false
rec: 3