Ansible: Output of 'loop' with 'register' module

Viewed 18

I'm trying to get the output of my Ansible script using register module but the loop I'm using is probably causing some issue.

Whats a default way of using register module with loop?

Code:

---
  - name:
    hosts:
    gather_facts:

    tasks:
        - name: Execute file
          ansible.builtin.shell: 
          environment:
                   "setting environment"
          register: output
          loop:
             "value"

         - debug:
              vars: output.std_lines
1 Answers

Whats a default way of using register module with loop?

It is just registering the result.

The only difference will be, that a single task will provide you just with an dictionary result (or output in your example) and registering in a loop will provide with a list result.results (or output.results in your example). To access the .stdout_lines you will need to loop over the result set .results too.

You may have a look into the following example playbook which will show some aspects of Registering variables, Loops, data structures, dicts and lists and type debugging.

---
- hosts: localhost
  become: false
  gather_facts: false

  tasks:

  - name: Create STDOUT output (single)
    command: 'echo "1"'
    register: result

  - name: Show full result (single)
    debug:
      var: result

  - name: Show '.stdout' (single)
    debug:
      msg: "The result in '.stdout': {{ result.stdout }} is of type {{ result.stdout | type_debug }}"

  - name: Create STDOUT output (loop)
    command: 'echo "{{ item }}"'
    register: result
    loop: [1, 2, 3]
    loop_control:
      label: "{{ item }}"

  - name: Show full result (loop)
    debug:
      var: result

  - name: Show '.stdout' (loop)
    debug:
      msg: "The result in '.stdout': {{ item.stdout }} is of type {{ item.stdout | type_debug }}"
    loop: "{{ result.results }}"
    loop_control:
      label: "{{ item.item }}"

By running it and going through the output you can get familiar with the differences in your tasks.

Further Q&A

... and many more here on SO.

Related