Omar BISTAMI
Omar BISTAMI

Reputation: 850

Ansible vars not substituting variables inside dictionary

I have the following variable and dictionary :

My_VAR1: "Hello"
My_VAR2: "My_DIC1"
My_DIC1: 
   key1: "{{ My_VAR1 }} World"
My_VAR3: "{{ vars[My_VAR2]['key1'] }}"

But its seems vars do not substitute the variable , i get the following output :

TASK [output : {{ My_VAR1 }} World] ***

Is there a way to force vars to substitute the variable and get the following output :

TASK [output : Hello World] ***

Upvotes: 1

Views: 136

Answers (1)

Vladimir Botka
Vladimir Botka

Reputation: 68034

Q: "Is there a way to force vars to substitute the variable and get the following output"

TASK [output : Hello World]

A: The play below

  vars:
    My_VAR1: Hello
    My_VAR2: "{{ My_VAR1 }} World"
    My_VAR3: "{{ My_VAR2 }}"
  tasks:
    - debug:
        var: My_VAR3

gives

"My_VAR3": "Hello World"

Q: "My_VAR2 is a dictionary ..."

A: Use lookup with vars plugin. The play below gives the same result.

  vars:
    My_VAR1: Hello
    My_DIC1:
      key1: "{{ My_VAR1 }} World"
    My_VAR2: "My_DIC1"
    My_VAR3: "{{ lookup('vars', My_VAR2).key1 }}"
  tasks:
    - debug:
        var: My_VAR3

Upvotes: 1

Related Questions