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
namehas aguestStateof"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
namehas itsguestStateset to"running". - Return
trueorfalsebased 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_jsonfilter converts the JSON string into a Python dictionary for further processing.
- The
-
Transform JSON to Formatted List:
- The
json_queryfilter restructures the JSON into a list of dictionaries withnameandguestStateattributes.
- The
-
Search in the List:
- The
selectattrfilter dynamically searches for items in the list:selectattr('name', 'equalto', search_name): Filters items with the specifiedname.selectattr('guestState', 'equalto', 'running'): Filters items with aguestStateof"running".
- The result is converted to a list and checked for length (
> 0) to returntrueorfalse.
- The
-
Display Results:
- The
debugmodule outputs whether the guest is running (trueorfalse).
- 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_nameis"baz", the result will be:TASK [Display the result] ******************************************** ok: [localhost] => { "msg": "Is guest running? true" } -
If the
search_nameis"nonexistent", the result will be:TASK [Display the result] ******************************************** ok: [localhost] => { "msg": "Is guest running? false" }
-
Key Benefits
-
Dynamic Search: The
selectattrfilter 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!