irom
irom

Reputation: 3606

How to iterate through dictionary with Ansible?

I have ansible task to read dictionary variable from yaml i.e. subnets[0] (in all.yml of group_vars). What if I want to iterate through whole dictionary ?

- name: Create and/or update the subnet
      azure_rm_subnet:
        name: "{{ subnets[0].name }}"
        address_prefix_cidr: "{{ subnets[0].prefix }}"
        route_table: "{{ subnets[0].udr }}"    

I tried with with_dict: "{{ subnets }}" and then i.e. item.value.name or item.name but playbook fails with an error. Also what if not all objects have all properties, i.e. subnets[1].udr is missing, will it be possible to check for existence of property in the task ? My all.yml file is like below:

subnets:
  - 
    name: subnet1
    prefix: 10.2.1.0/24
    udr: rt1
    nsg: sg1

  -
    name: subnet2
    prefix: 10.2.1.0/24
    nsg: sg1

Upvotes: 1

Views: 8137

Answers (1)

Ilhicas
Ilhicas

Reputation: 1507

That is closer to the with_items or with_subelements than it is with_dict

You would use it like this:

- name: Create and/or update the subnet
  azure_rm_subnet:
    name: "{{ item.name }}"
    address_prefix_cidr: "{{ item.prefix }}"
    route_table: "{{ item.udr }}"
  with_items:
    - "{{ subnets }}"

The subelements is in the case you ever have subelements of such items. Check the docs for further usages of loop control features in ansbile.

Upvotes: 4

Related Questions