Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 735
dsaydon Avatar asked Nov 09 '16 13:11

dsaydon


2 Answers

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.

like image 122
Konstantin Suvorov Avatar answered Oct 30 '22 00:10

Konstantin Suvorov


Try this

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

- name: init fact
  set_fact:
    rancher_env_hosts: "[]"

- name: test
  set_fact:
    rancher_env_hosts: "{{rancher_env_hosts}} + [ {{item.hostname}} ]"
  when: item.hostname | search(".*-i-.*")
  with_items: "{{hosts_json.json.data}}"

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

About search you can read here http://docs.ansible.com/ansible/playbooks_tests.html

UPD:
About adding values to array here: Is it possible to set a fact of an array in Ansible?

like image 44
Dmitry MiksIr Avatar answered Oct 30 '22 00:10

Dmitry MiksIr