Ansible: for each loop

March 29, 2019

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

Example for Python

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

Example for PHP

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

Example for 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 }}"