0

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
β.εηοιτ.βε
  • 33,893
  • 13
  • 69
  • 83

1 Answers1

1

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

U880D
  • 8,601
  • 6
  • 24
  • 40
  • Thx for your reply, but it is not what i asked for. I would like to construct my variable at play level, not inside the tasks section. We need vars.yaml variables values and system_environment value in order to build ansible_password, which is at play level. – alexander moro Jun 02 '22 at 12:53
  • Have you tested it? – U880D Jun 02 '22 at 12:59
  • @U880D I think you are confusing the OP by 1/ renaming their variable `environment_value` to `varKey`, 2/ using play vars instead of included vars or inventory vars. I agree with you that it is the same (except for the precedence of variables) but we do know that because we are used to it and we know how variable works, which seems to not be the case in the above question. – β.εηοιτ.βε Jun 02 '22 at 13:05