Venu S
Venu S

Reputation: 3691

ansible nested dictionary processing

I have this below task,

    - debug:
    msg: "Here: {{ item['containers'] }}"
  with_items: "{{ container_matrix['results'] }}"

which returns a dictionary with container name and its start up arguments. like : {"container-1":{"docker_run":"docker run -p 80:80 nginx", "env_file":"config1.env"}, "container-2":{"docker_run":"docker run -p 8080:80 nginx", "env_file":"config2.env"}

However I actually want to extract the container name and its env_file,

container_1 -> config1.env
container-2  -> config2.env

I tried several things, and none of the methods seem to work.

- debug:
    msg: "Here: {{ item }}"
  with_dict: "{{ container_matrix['results'].'containers'] }}"

is failing too.

can someone guide me in right direction.

Upvotes: 1

Views: 81

Answers (1)

Vladimir Botka
Vladimir Botka

Reputation: 68254

Given "a dictionary with container name and its start up arguments. like"

containers:
  "container-1": {"docker_run":"docker run -p 80:80 nginx", "env_file":"config1.env"}
  "container-2": {"docker_run":"docker run -p 8080:80 nginx", "env_file":"config2.env"}

The tasks

    - set_fact:
        mydata: "{{ containers|
                    dict2items|
                    json_query('[].{name: key, env_file: value.env_file}') }}"
    - debug:
        var: mydata

give

    "mydata": [
        {
            "env_file": "config1.env", 
            "name": "container-1"
        }, 
        {
            "env_file": "config2.env", 
            "name": "container-2"
        }
    ]

Upvotes: 2

Related Questions