Ansible JSON Query: Search & Extract Data with json_query
By Luca Berton · Published 2024-01-01 · Category: installation
How to search and extract JSON data in Ansible. Use json_query (JMESPath), from_json filter, and Jinja2 expressions to parse complex JSON structures.
Introduction
Ansible is a powerful tool used for automation and configuration management. While it is commonly associated with tasks like server provisioning and application deployment, its flexibility allows it to be used for a wide variety of tasks, even something as simple as searching for a specific band member in a list of bands. In this article, we'll create an Ansible playbook that searches for bands formed with a member named "Starr" and outputs the result.
Disclaimer
Full example: https://www.redhat.com/sysadmin/ansible-jinja-lists-dictionaries
The Playbook
Below is the Ansible playbook designed for this task. It includes a list of bands, each with its members, formation year, and the decade they were most active. The playbook filters through this list to find any band that has a member named "Starr."
Explanation of the Code • Playbook Structure: • The playbook targets the localhost and does not gather facts, as this is a simple data-processing task. • Variables Section: • The bands variable is defined as a list containing information about several bands, including their names, members, formation year, and the decade they were active. • Task: • A single task is defined that uses the ansible.builtin.debug module to filter through the bands list and find any band with a member named "Starr." • The filtering is done using Jinja2 templating with the selectattr filter, which searches for "Starr" within the members list of each band.
Running the Playbook
To run this playbook, save it as list_bands.yml and execute the following command in your terminal:
Expected Output
When the playbook is executed, the output will look like this:
Analysis of the Output
As shown in the output, the playbook successfully found that "The Beatles" is the band with a member named "Starr." The playbook executed successfully, with Ansible confirming that the task was "ok," meaning it completed as expected without any changes, failures, or other issues.
Conclusion
This example Playbooknstrates how Ansible's flexibility extends beyond traditional IT automation tasks. By leveraging Ansible's powerful templating system, you can automate various types of data processing tasks. This playbook, while simple, showcases the potential of Ansible for managing and filtering data, opening up a wide range of possibilities for its use in unconventional automation tasks.
Basic json_query
Nested Data
API Response Parsing
JMESPath Operations
Comparison Operators
| Operator | Example | |----------|---------| | == | [?status==\active\] | | != | [?status!=\deleted\] | | > | [?cpu>\4\] | | >= | [?ram>=\8\] | | && | [?role==\web\ && active] | | \|\| | [?env==\prod\ \|\| env==\staging\] | | ! | [?!disabled] |
Pipe Expressions
json_query vs Jinja2 Filters
| Use Case | json_query | Jinja2 | |----------|-----------|--------| | Simple attribute | ✓ | ✓ map(attribute=) | | Nested filtering | ✓✓✓ | Complex | | Aggregation (sum, max) | ✓✓ | sum(), max() | | Sorting | ✓✓ | sort(attribute=) | | Readability | Better for complex | Better for simple |
FAQ
"JMESPath requires jmespath" error?
Why use backticks in json_query?
JMESPath uses backticks for literal values: [?name==\alice\]. In Ansible YAML, escape them or use different quote styles.
Can I use json_query in when conditions?
Basic json_query
Install JMESPath
Common Queries
Parse JSON from Command Output
Complex Nested JSON
Filter with Comparison
json_query vs selectattr
Read JSON File
FAQ
json_query returns empty?
Check JMESPath syntax — backticks for literals: [?name==\alice\] not [?name=='alice'].
Can I use json_query without JMESPath?
No — json_query requires the jmespath Python library. Alternative: use Jinja2 selectattr, map, and reject filters.
How to pretty-print JSON?
Related Articles • Ansible Template Guide
Category: installation