Tamás Juhász
Tamás Juhász

Reputation: 699

Ansible Extract JSON Tag

I'm trying to work with Infoblox API, and it's responses. I would need to extract values of tags from the response, that seems to be in JSON format, but I cannot find the way to do it.

Here is my playbook:

- name: "Checking _node_exporter Service Record for {{ inventory_hostname }}"
  local_action:
    module: uri
    url: "{{ infobloxapiurl }}record:srv?name=_node_exporter.domain.com&target={{ inventory_hostname }}"
    force_basic_auth: yes
    user: "{{ infobloxuser }}"
    password: "{{ infobloxpassword }}"
    validate_certs: no
    return_content: yes
  register: _infoblox_results

- debug:
    var: _infoblox_results.json

The _infoblox_results.json variable looks like this:

TASK [prometheus : debug] *******************************************************************************************************************************************************************************************
task path: /ansible/roles/tasks/task.yml:38
ok: [server.domain.com] => {
    "_infoblox_results.json": [
        {
            "_ref": "record:srv/ZG5zLmJpbmRfc3J2JC5fZGVmYXVsdC5jb20udmNpbnQuZXcxL19ub2RlX2V4cG9ydGVyLzAvMC85MTAwL3Zhcm5pc2g3MDJ0c3QuZXcxLnZjaW50LmNvbQ:_node_exporter.domain.com/default",
            "name": "_node_exporter.domain.com",
            "port": 9100,
            "priority": 0,
            "target": "server.domain.com",
            "view": "default",
            "weight": 0
        }
    ]
}

I want to use the data of _ref from _infoblox_results.json, but I wasn't able to extract it with regex_replace (it drops back the full _infoblox_results.json):

- name: Get Record ID
  set_fact:
    _rcdid: "{{ _infoblox_results.json | regex_replace('record:srv.*\\/default,', '\\1') }}"

- debug:
    var: _rcdid
  when: _infoblox_results.json != []

Neither with json_query (it drops back nothing):

- name: Get Record ID
  set_fact:
    _rcdid: "{{ _infoblox_results.json | json_query('_ref') }}"

- debug:
    var: _rcdid
  when: _infoblox_results.json != []

Can someone please point me into the right direction?

Upvotes: 1

Views: 308

Answers (1)

techraf
techraf

Reputation: 68439

You have already an object in the memory, so simply refer to its value: _infoblox_results.json[0]._ref contains the string record:srv/ZG5zLmJpbmRfc3J2JC5fZGVmYXVsdC5jb20udmNpbnQuZXcxL19ub2RlX2V4cG9ydGVyLzAvMC85MTAwL3Zhcm5pc2g3MDJ0c3QuZXcxLnZjaW50LmNvbQ:_node_exporter.domain.com/default.

With that you can split the string and select the second element:

- name: Get Record ID
  set_fact:
    _rcdid: "{{ _infoblox_results.json[0]._ref.split('/')[1] }}"

Upvotes: 1

Related Questions