How to use a variable as index to an array

Hello,

I am trying to figure out the correct syntax for using a variable as an index to an array:

  • set_fact:
    cnt: “{{ response.stdout_lines | count - 1 }}”

filename: “{{ response.stdout_lines[3] }}”

filename: “{{ response.stdout_lines[{{cnt|int}}] }}”

The hardcoded lines[3] works fine, but how can I substitute a variable for the 3?

Thanks,
Joe

Curly brackets doesn't stack so remove the inner most ones.

filename: "{{ response.stdout_lines[cnt|int] }}"

Kai,
Ansible does not like that format either. Complains of undefined variable ‘cnt’ … (no {{ }} around it to avoid the stacking)
The error was: ‘cnt’ is undefined. Other ideas?

That's because you can't use a variable that is set in the same set_fact so they need to be two task.

- set_fact:
     cnt: "{{ response.stdout_lines | count - 1 }}"

- set_fact:
     filename: "{{ response.stdout_lines[cnt|int] }}"

That worked. Thanks!