Ansible: for each loop

March 29, 2019 - Last updated: November 7, 2019

Example of how to do a for each (foreach) loop in a task with a predefined dictionary.

Example on Python

for key, value in dictionary.items():
    # do stuff

Example on PHP

foreach ($dictionary as $key => $value) {
    # do stuff
}

Example on Ansible. The idea is iterate each element of the dictionary, include a file with a task and send as arguments the key and value.

dictionary:
  namespace1:
    - rule1
    - rule2
    - rule3
  namespace2:
    - rule2
    - rule4
- name: Foreach for Ansible
  include_tasks: task.yml
  with_items:
    - "{{ dictionary | dict2items }}"
  vars:
    key: "{{ item.key }}"
    value: "{{ item.value }}"

Related posts