Search code examples
jsonansibleslurp

How to import JSON file from a remote host into Ansible variable?


I am using ansible.builtin.slurp to do this. Here is the relevant part of my Ansible role:

- name: Load config
  slurp:
    src: "/etc/mlnx_snap/mlnx_snap.json"
  register: imported_config
- name: Debug
  debug:
    var: imported_config

I expect to have debug print my file, however, something different happens. Here's the file content:

root@ratchet01-snic:~# cat /etc/mlnx_snap/mlnx_snap.json
{
    "ctrl": {
        "sqes": 0x6,
        "cqes": 0x4,
        "cq_period": 3,
        "cq_max_count": 6,
        "nr_io_queues": 32,
        "mn": "Mellanox BlueField NVMe SNAP Controller",
        "sn": "MNC12",
        "mdts": 4,
        "oncs": 0,
        "offload": false,
        "max_namespaces": 0,
        "quirks": 0x0
    },
    "backends": [ {
        "type": "spdk_bdev",
        "paths": [{}]
    } ]
}

And here is what the debug output looks like:

Debug...
  retchet01-snic.mtr.labs.mlnx ok: {
    "changed": false,
    "imported_config": {
        "changed": false,
        "content": "LyoKICogcHJ...CiAgICB9IF0KfQo=",
        "encoding": "base64",
        "failed": false,
        "source": "/etc/mlnx_snap/mlnx_snap.json"
    }
}

Content is actually thousands of characters long, I just shortened it for readability.

Imagine I have a following task further in this role:

- name: Do x
  module_name:
    var_name: value
  when: imported_config.ctrl.quirks >= 0

How do I correctly import the JSON file so that such a task could work? What am I doing wrong?


Solution

  • The following helped get the raw text of JSON file:

    - name: Debug
      debug:
        var: imported_config.content|b64decode
    

    To further decode it into a variable, I would need to use this:

    - name: Debug
      debug:
        var: imported_config.content|b64decode|from_json
    

    That, however, fails for me due to invalid JSON format (it contains comments for some weird reason despite them not being allowed in JSON). But that is out of the initial scope of this question.