Can we use JSON to effectively compare various variables?

My current task involves comparing running services before and after a reboot on Linux servers. However, I am facing difficulty in getting the output to display the differences.

The function I have right now saves the pre/post state to disk. Ideally, I would like the output to be directly saved as a variable.

- name: populate service facts
  service_facts:
  register: facts

- name: Outputting running services
  debug: var=item
  with_items: "{{ facts|json_query(query)}}"
  vars:
    query: 'ansible_facts.services.* | [?state == `running`].name'

The desired function should look something like this:

    - name: Missing running services
      debug:
         msg: {{ item }}
      with_items:
        - {{ facts_pre }}
        - {{ facts_post }}
      vars:
        query: 'ansible_facts.services.* | [?state == `running`].name'
      when: facts_pre.ansible_facts.services != facts_post.ansible_facts.services

The expected result is similar to the following example of the server state before a reboot:

ok: [hostname] => (item=NetworkManager.service) => {
    "item": "NetworkManager.service"
}
ok: [hostname] => (item=systemd-udevd.service) => {
    "item": "systemd-udevd.service"
}
ok: [hostname] => (item=sshd.service) => {
    "item": "sshd.service"
}
ok: [hostname] => (item=systemd-journald.service) => {
    "item": "systemd-journald.service"
}

If journald fails during boot for any reason, it would look like this post-reboot:

ok: [hostname] => (item=NetworkManager.service) => {
    "item": "NetworkManager.service"
}
ok: [hostname] => (item=systemd-udevd.service) => {
    "item": "systemd-udevd.service"
}
ok: [hostname] => (item=sshd.service) => {
    "item": "sshd.service"
}

In this case, systemd-journald.service would be registered to its own variable.

Answer №1

This code snippet generates a list of currently running services:

- service_facts:
- set_fact:
    running_services_A: "{{ ansible_facts.services|dict2items|
                            json_query('[?value.state == `running`].key') }}"

If you need to compare the running services, you can utilize the difference filter like this:

- debug:
    msg: "Services running at A but not at B
          {{ running_services_A|difference(running_services_B) }}"

(not verified)


Additional Information

  • You do not need to store the output of service_facts. The ansible_facts.services variable is automatically created. Refer to service_facts documentation for more details.

Answer №2

One way to approach this scenario is by utilizing a with_items clause that finds the intersection of lists before and after reboot, allowing you to identify all differences between them.

Here is an example playbook featuring a sleep task that creates a delay for service manipulation from another session. This facilitates capturing changes in the facts_post variable:

---
- hosts: localhost
  gather_facts: false
  vars:
    web_folder:

  tasks:
  - name: populate service facts BEFORE
    service_facts:
    register: facts_pre

  - name: sleep to stop/start a service
    shell: sleep 10

  - name: populate service facts AFTER
    service_facts:
    register: facts_post

  - name: Missing running services
    debug:
       var: item
    with_items:
    - "{{ facts_pre | json_query(query) | symmetric_difference(facts_post | json_query(query)) }}"
    vars:
      query: 'ansible_facts.services.* | [?state == `running`].name'

I hope this solution proves useful!

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

Ways to extract information from a JSON array based on its length and content

Here is an example of some data: { "_id": ObjectId("528ae48e31bac2f78431d0ca"), "altitude": "110", "description": [ { "id": "2", "des": "test" } ], "id": "1", "latitude": "24.9528802429251", ...

Transforming lambda expressions into JSON objects using MongoDB .NET Driver

Struggling with mocking frameworks for unit tests, I find it easier to execute queries as strings rather than lambda expressions within my projects. This has led me to consider modifying my IDatabase interface: Interface IDatabase { IEnumerable<Use ...

Edit a specific portion of a document while disregarding the rest of the content

I am seeking to update a specific portion of a file with the following structure: { "Section_A": { "ws/abc-Location01": 24, "ws/abc-Location02": 67, "ws/abc-Location03: 101, }, "Section_B": { "ws/abc-Location01": 33, "ws/ab ...

Retrieve the JSON information and assign it to a variable

I'm currently working on a project that involves retrieving data through JSON and then displaying it in a datagrid. Here is the code snippet I am using to fetch the data: using (WebClient webClient = new WebClient()) { string email = loginDialo ...

Uncovering targeted terms within JSON structures with Python

I have developed an automation script to extract information from a word document and convert it into a JSON object. However, I am facing difficulty in retrieving specific values, particularly the applied voltage values of each test case, and storing them ...

The server's request is being processed through jQuery's ajax functionality

Recently, I've started working with jQuery and AJAX. Essentially, the webpage sends an HTTP post request, and the server-side DLL responds by writing a JSON-formatted response back to the page. I'm trying to understand how to handle this response ...

Steps to dynamically populate a datatable with JSON data by triggering a click event in jQuery

I am facing an issue with feeding JSON data into datatables when the search button is clicked. The JSON data structure is as follows: [ { "port_code":"BOM", "cont_details_id":"9", "price":"44.000", "cont_price":"500", "c ...

Sending JSON data to a targeted object in iOS

After reading numerous posts on Stack about POSTing data in XML and JSON, I am still having trouble finding specific information on how to update a selected object. I am successfully retrieving data from my boss' job tracking API and everything seems ...

Access JSON data from the data[] object in PHP and handle it

I have a task where I need to extract specific data from Facebook using the following code snippet: $tagData = file_get_contents('https://graph.facebook.com/123456789/friends?access_token='.$access_token); echo $tagData; When this runs, it gen ...

Is there a way to transfer an array of strings and integers from JavaScript to Python 3.8?

I have reviewed similar questions but haven't found a solution that works for me. My inquiry is regarding the following code snippet: function pyInput(){ const buffers = []; proc.stdout.on('data', (chunk) => buffers.push(chunk)) ...

Parsing JSON using Gson with the same key but different values

This is an example of a JSON event: { "type":"record", "name":"Doc", "doc":"adoc", "fields":[ { "name":"id", "type":"string" }, { "name":"user_friends_count", "type":[ "int", "null" ...

Is it important to clean user input before displaying it on the screen while also permitting all characters

Currently, I have a JavaScript function that limits the characters accepted for user input in order to safely display it in the DOM. Now, I want to allow all characters while still encoding them to prevent any malicious scripts from executing. How can I a ...

Jackson encounters difficulty when trying to serialize Joda DateTimeFormatter

I'm having trouble returning a JSON response in my Spring MVC 3 application, specifically with Joda's DateTimeFormatter. com.fasterxml.jackson.databind.JsonMappingException: No serializer found for class org.joda.time.format.DateTimeFormat$Style ...

Exploring the Power of JSON in HighCharts

For creating the series, I am utilizing a ViewModel in the following manner: namespace AESSmart.ViewModels { public class HighChartsPoint { public double x { set; get; } public double y { set; get; } public string color { set; get; } p ...

What is the best way to use the $push operation to add an object to an array within a mongoDB database using Node.js

I am trying to find a way to push an object into an array inside my MongoDB database. When using the $push method with submits[postDate], I am encountering an error with the syntax highlighting the first "[". Any suggestions on how to resolve this issue? ...

Format JSON data with each object appearing on a new row

Has anyone found a solution for importing test data to mongodb using mongo atlas when each document needs to be on a separate line? I'm wondering if there are any online tools available to assist with formatting or if I should create my own script. ...

Is there any method to prevent the default icon from showing up and disable the one-click functionality?

package.json: { "name": "password-generator-unique", "productName": "Unique Password Generator", "version": "1.0.0", "description": "Custom password generation desktop tool& ...

Is it possible to change JSON null to nan in the simplejson.load() function?

When it comes to handling NaN --> null conversions from Python to JSON, I have relied on the simplejson module. Specifically: To handle NaN values, I have been using the ignore_nan=True flag in the simplejson.dump function. However, I have not been able ...

The error message "TypeError list indices must be integers not str" arises when trying to access a

Currently, I am exploring the world of Python and APIs, specifically experimenting with the World Cup API accessible at . This is a sample snippet of the JSON data: [ { "firstName": "Nicolas Alexis Julio", "lastName": "N'Koulou N'Doub ...

python: understanding the behavior of json.dumps with dictionaries

My goal is to modify the behavior of the dict when using json.dumps. I want to be able to order the keys, so I created a new class that inherits from dict and overrides some of its methods. import json class A(dict): def __iter__(self): for i ...