How to refer to a variable within a list in var file in Ansible?

Viewed 1641

I have a variable file that includes a list like below format:

VAR:
  - a: 1
    b: 2
    c: 3
  - a: 4 
    b: 5
    c: 6

Here, I want to add another variable referencing a sub variable within a list, for example:

VAR:
  - a: 1
    b: 2
    c: 3
    d: "{{ VAR.0.a }}"
  - a: 4 
    b: 5
    c: 6
    d: "{{ VAR.1.a }}"

But they didn't work.

I tried {{ VAR[0].a }} {{ VAR[a] }} {{ VAR.0.a }} and etc, but none of them worked.

How do you refer to a sub element within a list?

1 Answers

I think a proper way would be {{ VAR[0]["a"] }}. But there is a big chance that thing you want to do wouldn't work.

The reason is that 'mustaches do not stack'. If you are using somewhere in your code 'VAR.d', it will be expanded to string 'VAR[0]["a"]' (not an expression, but a literal string). Ansible uses a lazy templatization, delaying template expansion up to the last possible moment. It can be partially overridden by set_fact module, but I doubt it would help in this situation.

My advice is to avoid such references.

But here is a YAML trick to the rescue. It has nothing to do with Ansible, nevertheless it works in Ansible.

YAML allows to use references to old values.

VAR:
  - a: &refname 1
    b: 2
    c: 3
    d: *refname
  - a: &ref2 4 
    b: 5
    c: 6
    d: *ref2
Related