While developing Ansible playbook for my on project I have some one usecase regarding use variable of variable in ansible playbook. So I found some workaround as I described in my this article.

Problem :-

I am trying to access variables which is defined in `group_vars`.  As we know variable defined in group_vars are accessible from ansible playbook.

group_vars/all

parent1:
  child1: somevalue1
  child2: somevalue2
parent2:
  child1: somevalue1
  child2: somevalue2

Now I am passing parent detail from ansible playbook from extra vars like
this

ansible-playbook playbook.yml -e "parent=parent1"

Now How can I access parent1.child1 value where parent1 comes in {{ parent }} vars?

Answer is no.

Solution:-

I have added group_vars variables under one variable called data like below

data:
  parent1:
   child1: somevalue1
   child2: somevalue2
  parent2:
   child1: somevalue1
   child2: somevalue2

In my playbook I am able to access parent1.child1 below in variable

{{ data[parent].child1 }}

My playbook code look like this

- hosts: local
  user: roop
  gather_facts: no
  connection: local
  vars:
    parent: ""
  tasks:
  #get parent value
  - debug: msg={{ parent }}
  #trying to access parent1.child1 value here
  - debug: msg={{ data[parent].child1 }}
(Visited 904 times, 19 visits today)