Interview Prep/Ansible/Jinja2, Conditionals and Loops

When do you use `json_query` versus `selectattr`/`map`?

AdvancedConceptJinja2, Conditionals and Loops
Answer

json_query (from community.general) uses JMESPath for complex queries on nested JSON, such as cloud API results. It needs the jmespath Python library on the controller.

running: "{{ ec2.instances | community.general.json_query('[?state.name==`running`].instance_id') }}"

Native filters (selectattr, map, selectattr('x','equalto',y)) need no extra dependency and are easier to debug. Use json_query when the structure is deeply nested or needs projection of several fields at once. Backticks mark literals in JMESPath, which is why quoting often goes wrong.

All Ansible questions Roadmap: Ansible

More on Jinja2, Conditionals and Loops