Register variables in with_items loop in Ansible playbook

So how can I properly save the results of the operations in variable names based on the list I iterate over?

You don’t need to. Variables registered for a task that has with_items have different format, they contain results for all items.

- hosts: localhost
  gather_facts: no
  vars:
    images:
      - foo
      - bar
  tasks:
    - shell: "echo result-{{item}}"
      register: "r"
      with_items: "{{ images }}"

    - debug: var=r

    - debug: msg="item.item={{item.item}}, item.stdout={{item.stdout}}, item.changed={{item.changed}}"
      with_items: "{{r.results}}"

    - debug: msg="Gets printed only if this item changed - {{item}}"
      when: item.changed == true
      with_items: "{{r.results}}"

Leave a Comment