Strategies for sorting through Ansible JSON data efficiently

Utilizing Ansible Automation for Linux Patching. After completing the patching process, I need to extract specific details from the JSON output.

Below is the code snippet that does not provide accurate output from the JSON file when executing the playbook:

Playbook 1

---
- hosts: localhost
  gather_facts: no
  vars:
    contents: "{{ lookup('file', '/ansible/linuxpatch.json') | from_json }}"
  tasks:
    - name: calling file
      debug:
        msg={{ contents.msg | list }}
      register: msg

    - name: update
      set_fact:
        result: "{{ msg | json_query('*.Installed') }}"

Playbook 2

    - name: report update count
      set_fact:
        update_info: "{{ msg | to_json | from_json | json_query(update_info_query) }}"
      vars:
        update_info_query: >
          *[].{
            Installed: Installed,
          }

I only require the Installed details from the JSON output.

JSON Output

{ 
... (JSON output remains unchanged)

The approach works with the JSON output file, but integrating it into the actual playbook raises an error.

When attempting to incorporate it into the playbook, errors are encountered as shown below:


  • hosts: prod become: yes #become_user: root tasks:
      ... (Additional task details remain unchanged)

Answer №1

The code snippet below will achieve the desired outcome

    installed: "{{ contents.msg.2 | map('from_yaml') |
                                    json_query('[].Installed') }}"

Here is an example of a full playbook for testing purposes

- hosts: localhost

  vars:

    contents: "{{ lookup('file', 'linuxpatch.json') | from_yaml }}"
    installed: "{{ contents.msg.2 | map('from_yaml') |
                                    json_query('[].Installed') }}"

  tasks:

    - debug:
        var: installed

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Encoding a string in JSON that contains the "#" symbol along with other special characters

The client side javascript code I have is as follows: <html> <script type="text/javascript" src="js/jquery.min.js"></script> <script> $(document).ready(function() { //var parameters = "a=" + JSON.stringify( ...

How can I prevent writeFileSync from replacing existing data?

When I use this line of code, it deletes all existing data. Is there a method or function that will append the new data on a new line instead? fs.writeFileSync(path.resolve(__dirname, 'quotes.json'), JSON.stringify(quotey)); ...

Extracting data from a JSON object

Currently, I am facing an issue with my node.js code that is not working as expected when trying to fetch a value from a 3rd party website in JSON format. Although my code works fine for similar cases, it is failing to extract the price of a specific item ...

Error: JSON at position 1 is throwing off the syntax in EXPRESS due to an unexpected token "

I'm currently utilizing a REST web service within Express and I am looking to retrieve an object that includes the specified hours. var express = require('express'); var router = express.Router(); /* GET home page. ...

Transmit data using both jQuery and JSON technology

I'm struggling to figure out how to send a JSON structure with a file using AJAX. Whenever I try to include an image in the structure, I encounter an error. var professionalCardNumber = $("#professional_card_number_input").val(); var professi ...

Is there a specific method to access a JSON file with (js/node.js)?

Searching for a way to access user information stored in a JSON file using the fs module in node.js. Specifically looking to read only one user at a time. app.get("/1", function(req, res) { fs.readFile("users.json",function(data, err){res.write(data)}} W ...

Utilize Mongoose to seamlessly integrate online shopping cart items into MongoDB

I am facing an issue while trying to insert a shopping cart of items in the form of a JSON object into a MongoDB collection using a mongoose schema. Although the customer's ID is successfully stored (extracted from the User DB), unfortunately, the ca ...

Having trouble accessing JSON file again: "Encountered unexpected end of input error"

I have set up a cron-based scheduler to periodically retrieve JSON data from an external API every 2 minutes. The process involves writing the data to a file, reading it, cleaning it, and then storing it in a MongoDB collection. Everything works smoothly o ...

The compatibility between Node.js and Git seems to be lacking

I'm attempting to set up automatic deployment with GitHub. I have created a JavaScript file to act as a "server" to receive the hook from GitHub, and that part is working flawlessly. However, I'm struggling with getting my hook.sh script to execu ...

ExpressJs res.json throwing error - Headers cannot be set after they have already been sent

In my current project using ExpressJS, I have a specific route set up like this: router.route('/monitor') .all(function (req, res, next) { next(); }).get(monitor.monitorServers); There is also a controller named 'monitor' which co ...

What is a way to nest a promise request within another request?

Q: How can I create a new promise within a request, and then return it in a nested request? Here is the code snippet: request({ // --------------request 1------------ url: request_data.url, method: request_data.method, form: request_data.data ...

Creating dynamic email content with Node.js using SendGrid templating

How can I properly format SendGrid's content using Node.js? I'm currently working on sending emails from a contact form within an application using SendGrid. I have a Google Cloud Function set up that I call via an HTTP post request. Although I ...

Converting Plain JSON Objects into a Hierarchical Folder Structure using Logic

Looking at the data provided below: [ {name: 'SubFolder1', parent: 'Folder1'}, {name: 'SubFolder2', parent: 'SubFolder1'}, {name: 'SubFolder3', parent: 'SubFolder2'}, {name: 'Document ...

Array of JSON data passed in the request body

Recently, I have been attempting to pass JSON data to my req.body. The data structure is as follows: answers = ["A","B"]; //An array to be included in the JSON Object var Student_Answers = { //JSON object definition Answers: answers, matricNumber: ...

What is the best way to merge an array into a single object?

I have an array object structured like this. [ { "name": "name1", "type": "type1", "car": "car1", "speed": 1 }, { "name": &q ...

Accessing a particular level within a JSON object in Node.js

I'm dealing with a two level JSON structure {"Policy": { "Channel": "online", "Credit Score": "20000", "Car": [{ "Age": "28", ...

What is the best way to eliminate or substitute Unicode Characters in Node.js 16?

Currently, I have a file that is being read into a JSON Object. { "city": "Delicias", "address": "FRANCISCO DOMÍN\u0002GUEZ 9" } We are using this address to send it to the Google Maps API in order to ...

Troubleshooting: Node.js Express Server GET Handler Failing to Function

Recently, I've been attempting to build a GET request handler in Express.js. Here's the snippet of code I've put together: // include necessary files and packages const express = require('./data.json'); var app = express(); var m ...

I encountered a ReferenceError stating that the variable "html" is not defined

Recently, I delved into the world of Node.js for the first time. During my attempt to connect my index.html file, an error message stating 'ReferenceError: html is not defined' popped up. Below is the code snippet from my index.js: var http = re ...

The collaboration between a JSON response and Node.js allows for seamless

Within my node app, I am passing a series of queries as an Object. It is crucial for me to structure the request in an exact format. Here is an example of my request: {q0:{query0},q1:{query1},q2:{query1}} The expected response should look like this: {q0 ...