Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Ansible to print the variable value having another variable inside it

In a.yml file, I have stored data like below

---
 Server:
   "Node1" : ["Node1", "Owner1", "ID1"]
   "Node2" : ["Node2", "Owner2", "ID2"]

Now, in xyz.yml playbook, I tried to debug a variable as below and I am passing the Node_Name in commandline (ansible-playbook xyz.yml -e "Node_Name=Node1")

---
 - name: "Print Variable value"
   hosts: all
   gather_facts: no
   vars:
     Node_Name: Node
     ID_Name: "{{ Server.{{ data1 }}[2] }}"
   tasks:
   - name: "Print the id"
     debug:
       msg:
         - "The id is {{ ID_Name }}"

But this is failing with error – Template error while templating string :expected name or number

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Can someone please help to fix this and let me know how can I get the ID printed as output. Here expected output is ID1

>Solution :

You never nest {{...}} markers.

Recall that to access a nested variable. the syntax Server.Node1 is exactly equivalent to Server["Node1"]. The second syntax allows us to make use of variables (and string interpolation) on the key, so we can write:

Server[Node_Name]

In other words:

- name: "Print Variable value"
  hosts: all
  gather_facts: no
  vars:
    Node_Name: Node
    ID_Name: "{{ Server[Node_Name][2] }}"
  tasks:
  - name: "Print the id"
    debug:
      msg:
        - "The id is {{ ID_Name }}"
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading