0

I am trying to access variables which is defined in group_vars

group_vars/all

parent1:
  child1: somevalue1
  child2: somevalue2

parent2:
  child1: somevalue1
  child2: somevalue2

Now I am passing parent detail from ansible playbook 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?

My playbook look like this:-

playbook.yml

- 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={{ {{ parent }}.child1 }}

Playbook output:-

PLAY [local] ******************************************************************

TASK: [debug msg=local] *******************************************************
ok: [127.0.0.1] => {
    "msg": "parent1"
}

TASK: [debug msg={{{{parent}}.child1}}] ***************************************
ok: [127.0.0.1] => {
    "msg": "{{{{parent}}.child1}}"
}

PLAY RECAP ********************************************************************
127.0.0.1                  : ok=2    changed=0    unreachable=0    failed=0

Can anyone guide how can I achieve this or any alternate solution.

1 Answer 1

3

How I have done this

Change group_vars/all like below:-

data:
    parent1:
      child1: somevalue1
      child2: somevalue2

    parent2:
      child1: somevalue1
      child2: somevalue2

Change in playbook.yml:-

 - debug: msg={{ data[parent].child1 }}

Please share if you have any better solution :)

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.