Ansible: How to iterate an array with a variable number in a variable

Viewed 458

I have an array, coming from the registered results of a loop.
It has 4 elements.
I want to go through the items of the array, with the loop, with sequence: 0-3 (3, means last element).
When I do "hardcoded, as follows, all fine, I get the results I want.
But I do not know how to put the sequence variable inside the results variable, Can someone guide me, please?

Working code:

- name: Show output array
  debug:
    msg:
      - "{{ output.results[0] }}" # This also works
      - "{{ output.results.0.stdout }}"
      - "{{ output.results.1.stdout }}"
      - "{{ output.results.2.stdout }}"
      - "{{ output.results.3.stdout }}"
  run_once: yes

Non-working code (Syntaxe error)

 - name: Show output array
  debug:
    msg:
      - "{{ output.results[my_item] }}" # Not Working
      - "{{ output.results.{{ my_item }}.stdout }}" # Not working
      - "{{ output.results.(my_item|int) }}" # Tried hard with lot of patterns.. Still KO
  run_once: yes
  with_sequence: 0-{{ output.results | length -1 }} # This works, tested
  loop_control:
    loop_var: my_item

TASK [Show output array] ************************************************************************************************ fatal: [localhost]: FAILED! => {"msg": "template error while templating string: expected name or number. String: {{ output.results.{{ my_item }}.stdout }}"

1 Answers

I have an array, coming from the registered results of a loop.

From your question it seems you are getting an array in output.results[0-n]. Also you have 3 messages in the debug task. The error is for the 2nd message:

- "{{ output.results.{{ my_item }}.stdout }}" # Not working

And it is complaining about unnecessary {{ .. }} inside an already open Jinja context.

The easy approach:

As output.results is an array already, you can directly loop over it, and just get item.stdout.

Example:

    - debug:
        msg: "{{ item.stdout }}"
      with_items: "{{ output.results }}"

Using a sequence or range:

Using range in example as with_sequence is replaced by loop. From documentation:

with_sequence is replaced by loop and the range function, and potentially the format filter.

    - debug:
        msg: "{{ output.results[my_item].stdout }}"
      loop: "{{ range(0, output.results|length) | list }}"
      loop_control:
        loop_var: my_item
Related