dsaydon dsaydon - 29 days ago 20
JSON Question

ansible parse json with several keys with the same name to one list variable

I have an issue to parse a json using ansible
I have a task that connected to rancher and get a json file

task:

- uri:
url: http://rancher.local:8080/v1/hosts
method: GET
user: ##################
password: ################
body_format: json
register: hosts_json

- name: test
set_fact:
rancher_env_hosts: "{{ item.hostname }}"
#when: item.hostname == "*-i-*"
with_items: "{{hosts_json.json.data}}"

- name: output
debug:
msg: "hosts: {{rancher_env_hosts}}"


and I get the following json (after edit it to be more readable):

{
"json": {
"data": [
{
"hostname": "rancher-i-host-02",
"id": "adsfsa"
},
{
"hostname": "rancher-i-host-01",
"id": "gfdgfdg"
},
{
"hostname": "rancher-q-host-01",
"id": "dfgdg"
},
{
"hostname": "rancher-q-host-02",
"id": "dfgdg"
}
]

}

}


When I start the playbook I get only the last host name in the variable and not all the list of hostname. can I register all the list to the same variable?

In addition, I also added a line with the a comment "#" in order to get only the host names that match the string "-i-" bit it's not working. any idea?

Answer

This is what filters (and this) for:

- set_fact:
    hosts_all: "{{ hosts_json.json.data | map(attribute='hostname') | list }}"
    hosts_i: "{{ hosts_json.json.data | map(attribute='hostname') | map('regex_search','.*-i-.*') | select('string') | list }}"

host_all will contain all hostnames, host_i will contain only .*-i-.* matching hostnames.