Determine‌ ‌Index‌ ‌of‌ ‌Array‌ ‌in‌ ‌Ansible

There are use cases when you need to determine‌ ‌index‌ ‌of‌ ‌array‌ ‌in‌ ‌Ansible. If you have an array or list as such array_name = [“cat”, “dog”, “rabbit”, “fish”]. You may want a task to run  if the element is for example dog and  get the index of dog in the array/list to use later down the playbook. Determining the ‌index‌ ‌of‌ ‌‌array‌ ‌in‌ ‌Ansible can be achieved using with_indexed_items (with_ style family loop) or just regular loop.

In this post, I’m going to assume the variable array_name has been defined somewhere.

-     name: Get index of a list
        value: "{{ index | int}}"
      loop: "{{ array_name | flatten(levels=1)  }}"
      when: item == "dog"
        index_var: index

Or using the —-

-     name: Get index of a list
        value: "{{ item.0 | int}}"
      with_indexed_items: "{{ array_name }}"
      when: item.1 == "dog"

These tasks will both output
ok: [localhost] => {
“value”: 1

Integer value 1.
Make sure you have 
jinja2_native = True
in your ansible.cfg file. Otherwise, value will be a string and not an integer.

Watch out for a post on this that explains the two lines

Leave a Reply