ansible iterate over only one type of elements in dictionary

Viewed 29

I have vars defined like this:

x_named_zones:
  - name: 'example1.com'
    type: 'dynamic'
  - name: 'example2.org'
    type: 'dynamic'
  - name: 'example3.tld'
    type: 'master'

and I would like to iterate over them with a task:

- name: loop over the list
  debug:
    msg: 'name: {{ item.name }} type: {{ item.type }}'
  loop: '{{ x_named_zones }}'

and this works. But how can I loop over the list where the type: dynamic only? So the expected result of the loop task would be:

example1.com and example2.org

1 Answers

Select the items you want

- name: loop over the list
  debug:
    msg: "name: {{ item.name }} type: {{ item.type }}"
  loop: "{{ x_named_zones|selectattr('type', 'eq', 'dynamic') }}"

Notes

  • The iteration will fail if the atribute type is missing in any of the items. For example, iteration of the data below
    x_named_zones:
      - name: 'example1.com'
        type: 'dynamic'
      - name: 'example2.org'
        type: 'dynamic'
      - name: 'example3.tld'
        type: 'master'
      - name: 'example4.tld'
        misc: 'master backup'

will fail

TASK [loop over the list] *************************************************************
fatal: [localhost]: FAILED! => 
  msg: '''dict object'' has no attribute ''type'''

In this case, you can use the filter json_query. This filter ignores missing attributes. For example,

    - name: loop over the list
      debug:
        msg: "name: {{ item.name }} type: {{ item.type }}"
      loop: "{{ x_named_zones|json_query('[?type == `dynamic`]') }}"

gives (abridged)

msg: 'name: example1.com type: dynamic'
msg: 'name: example2.org type: dynamic'
  • Update the items of the list with default type if you are not able, or don't want to use json_query. For example,
default_type: 'static'
x_named_zones_update: "{{ [{'type': default_type}]|
                          product(x_named_zones)|
                          map('combine')|
                          list }}"

gives

x_named_zones_update:
  - name: example1.com
    type: dynamic
  - name: example2.org
    type: dynamic
  - name: example3.tld
    type: master
  - misc: master backup
    name: example4.tld
    type: static
Related