Ansible – execute role in a loop for items in yaml inventory file

In case you have an inventory yaml file of whitespace indentation:

  dictionary:
    items:
      item1:
        name: "Item-1"
        settings:
          description: "My item 1"
      item2:
        name: "Item-2"
        settings:
          description: "My item 2"

and you would like to execute a role for the number of keys in the dictionary, you can do the following:

    - include_role:
        name: my_role_name
      loop: "{{ dictionary.items | dict2items }}" # loops are possible only over lists in yaml so we convert the whitespace (dict) to list here
      loop_control:
        index_var: myitem #index number
      vars:
        item_index: "{{ myitem + 1 }}"
        cloud_element: "{{ dictionary.items[ 'item' + item_index] }}"
        ansible_facts_output_var: "logalert{{ item + 1 }}"

Powered by BetterDocs

Leave a Reply