Introduction
Handling JSON data is a common task in IT automation workflows. Ansible simplifies this process with filters like from_json
, json_query
, and selectattr
. This guide demonstrates how to:
- Parse JSON data into a Python dictionary.
- Transform the data into a structured list.
- Search for specific criteria (e.g., if a
name
has aguestState
of"running"
).
Use Case: Verify If a Guest Is Running
Imagine receiving JSON data from an API or file, containing details about virtual machine states. Your task is to:
- Transform this JSON data into a structured format.
- Check if a specific
name
has itsguestState
set to"running"
. - Return
true
orfalse
based on the search.
The Ansible Playbook
Here’s how to achieve this:
Playbook Example
---
- hosts: localhost
gather_facts: false
vars:
search_name: "baz" # The name to search for
tasks:
- name: Define Raw JSON String (Example)
set_fact:
raw_json_string: >
{
"results": [
{ "instance": { "guest": { "guestState": "running" } }, "item": "foo" },
{ "instance": { "guest": { "guestState": "running" } }, "item": "bar" },
{ "instance": { "guest": { "guestState": "running" } }, "item": "baz" },
{ "instance": { "guest": { "guestState": "running" } }, "item": "qux" },
{ "instance": { "guest": { "guestState": "running" } }, "item": "quux" }
]
}
- name: Parse JSON string to dictionary
set_fact:
json_data: "{{ raw_json_string | from_json }}"
- name: Transform JSON to formatted list
set_fact:
formatted_list: "{{ json_data.results | json_query('[].{name: item, guestState: instance.guest.guestState}') }}"
- name: Check if guestState is running for a specific name
set_fact:
guest_running: "{{ formatted_list | selectattr('name', 'equalto', search_name) | selectattr('guestState', 'equalto', 'running') | list | length > 0 }}"
- name: Display the result
debug:
msg: "Is guest running? {{ guest_running }}"
Explanation
Key Sections
Define Raw JSON String:
- A sample JSON string is defined using
set_fact
. In real-world scenarios, this data may come from an API or file.
- A sample JSON string is defined using
Parse JSON to Dictionary:
- The
from_json
filter converts the JSON string into a Python dictionary for further processing.
- The
Transform JSON to Formatted List:
- The
json_query
filter restructures the JSON into a list of dictionaries withname
andguestState
attributes.
- The
Search in the List:
- The
selectattr
filter dynamically searches for items in the list:selectattr('name', 'equalto', search_name)
: Filters items with the specifiedname
.selectattr('guestState', 'equalto', 'running')
: Filters items with aguestState
of"running"
.
- The result is converted to a list and checked for length (
> 0
) to returntrue
orfalse
.
- The
Display Results:
- The
debug
module outputs whether the guest is running (true
orfalse
).
- The
Running the Playbook
Save the Playbook:
- Save the code as
transform_and_search.yml
.
- Save the code as
Execute the Playbook:
ansible-playbook transform_and_search.yml
Output:
If the
search_name
is"baz"
, the result will be:TASK [Display the result] ******************************************** ok: [localhost] => { "msg": "Is guest running? true" }
If the
search_name
is"nonexistent"
, the result will be:TASK [Display the result] ******************************************** ok: [localhost] => { "msg": "Is guest running? false" }
Key Benefits
Dynamic Search: The
selectattr
filter provides a concise and efficient way to search data based on multiple conditions.Reusable Code: You can adapt this pattern to other JSON data transformations and searches.
Error Handling: The search logic ensures accurate results and avoids processing empty or invalid data.
Conclusion
By combining JSON parsing with dynamic filtering, Ansible allows you to handle and query complex data structures efficiently. Whether you’re automating virtual machine states or managing API responses, these techniques provide a robust solution. Try this approach in your automation workflows and unlock new possibilities with Ansible!
Subscribe to the YouTube channel, Medium, and Website, X (formerly Twitter) to not miss the next episode of the Ansible Pilot.Academy
Learn the Ansible automation technology with real-life examples in my Udemy 300+ Lessons Video Course.
Explore my book Ansible By Examples: 200+ Automation Examples for Linux and Windows System Administrators and DevOps:
Donate
Support this project and keep learning resources alive: Patreon Buy me a Pizza