Bootstrap FreeKB - Ansible - Get index number of an element in a list using index_of
Ansible - Get index number of an element in a list using index_of

Updated:   |  Ansible articles

If you are not familiar with modules, check out Ansible - Getting Started with Modules.

The index_of module can be used to get the index number of an element in an array/list. 

AVOID TROUBLE

The index_of module is part of the ansible.utils collection. The ansible-galaxy collection install ansible.utils command can be used to install the ansible.utils collection.

In this example, the "fruit" array contains two elements.

  • apple = index 0
  • banana = index 1

This playbook will get the index number of "banana" in the "fruit" array.

---
- hosts: localhost
  gather_facts: false
  vars:
    fruit:
     - apple
     - banana
  tasks:
  - debug:
      msg: "banana index number = {{ lookup('ansible.utils.index_of', fruit, 'regex', 'banana') }}"
...

 

Running this playbook should return the following.

ok: [localhost] => {
    "msg": "banana index number = 1"
}

 

In this example, "food" contains key value pairs. Here is how you would get the index number of the element that has the key named "fruit" and a value containing "banana".

---
- hosts: localhost
  gather_facts: false
  vars:
    food:
      - { fruit: 'banana' }
      - { fruit: 'orange' }
      - { veggy: 'onion' }
      - { veggy: 'pepper' }
  tasks:
  - debug:
      msg: "fruit banana index number = {{ lookup('ansible.utils.index_of', food, 'regex', 'banana', 'fruit') }}"
...

 

Running this playbook should return the following.

ok: [localhost] => {
    "msg": "fruit banana index number = 0"
}



Did you find this article helpful?

If so, consider buying me a coffee over at Buy Me A Coffee



Comments


Add a Comment


Please enter 278ab8 in the box below so that we can be sure you are a human.