1

I am trying to match certain key from an ansible output/vars, and return the value of another key.

Here is my vars.

{
    "_meta": {
        "hostvars": {
            "ansibletower1_422c3aed-780c-8c33-3054-d32e330c9285": {
                "guest.hostName": "ansibletower1.rh.pro",
                "name": "ansibletower1"
            },
            "child domain_422c4cd1-d644-7eeb-df7c-c32a2a05c030": {
                "guest.hostName": null,
                "name": "child domain"
            }
        }
    }
}

My non-working playbook

- hosts: ansibletower1.rh.pro
  tasks:
      - debug:
          msg: "{{ _meta | json_query(querystr) }}"
        vars:
          querystr: "[?hostvars.*.\"guest.hostName\"=='{{inventory_hostname}}'].name"

I am trying to follow the method here, https://blog.networktocode.com/post/ansible-filtering-json-query/. However in my scenario is not array, which is different than the example in the link.

My end goal is to match guest.hostName with {{ inventory_hostname }}, and return the value of the name by using - set_fact: to register it to another variable.

sloweriang
  • 308
  • 4
  • 19

1 Answers1

1

I'd try with:

tasks:
  - name: Loop over data and continue if string was found.
    debug:
      msg: "{{ _meta | json_query(querystr) }}"
    vars:
      querystr: "hostvars.* | [?\"guest.hostName\"==`{{inventory_hostname}}`].name"

when you select all keys with .* you get an array back, so it is piped into another query that filters and returns name.

guido
  • 18,864
  • 6
  • 70
  • 95