alexander moro
alexander moro

Reputation: 1

Build variable name at play level

I want to build a variable name at play level which is the result of different variables.
In the following example I need to replace TEST (that is included in vars.yaml) by a variable name which comes from the inventory.

E.g.

playbook.yaml

--- 
- hosts: server1
  gather_facts: true
  vars_files: 
    - vars.yaml

  vars:
    ansible_password: '{{ var1.name1.TEST }}'

  tasks:

    - debug:
        msg: '{{ ansible_password }}'

vars.yaml

var1:
  name1:
    TEST: "prova"

server1 hostvars

environment_value: TEST

Upvotes: 0

Views: 263

Answers (1)

U880D
U880D

Reputation: 12071

According your use case description and example I understand that you wonder How to construct a variable from another variable and then fetch it's value.

One possible approach could be

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

  vars:

    var1:
      name1:
        TEST: "prova"

    varKey: "TEST"

    dynVar: "{{  var1.name1[varKey] }}"

  tasks:

  - name: Show variable dynamic
    debug:
      msg: "{{ var1.name1[varKey] }} and {{ dynVar }}"

resulting into an output of

TASK [Show variable dynamic] ******
ok: [localhost] =>
  msg: prova and prova

Further Q&A

Upvotes: 1

Related Questions