Ansible variable inside variable.

 Lets assume there is a json with following structure

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
{
    "dev":{
      "app_1":{
          "key":"element",
          "value":"somevalue"
      },
      "app_2":{
          "key":"element",
          "value":"somevalue"
      }  
    },
    "test":{
        "app_1":{
          "key":"element",
          "value":"somevalue"
      },
      "app_2":{
          "key":"element",
          "value":"somevalue"
      }  
    },
    "production":{
        "app_1":{
          "key":"element",
          "value":"somevalue"
      },
      "app_2":{
          "key":"element",
          "value":"somevalue"
      }  
    }
}

From this json we have to extract values using the Ansible. As you see "key" and "value" fields are constant and we have variable environment ("dev", "app", "production") and app name ("app_1", "app_2")

We have an Ansible playbook where we have "Environment" and "Application Name" as part of arguments, where we have to read the respective values from the above JSON.

Let's assume that JSON is downloaded from somewhere. In this sample, we are saving ourselves from that complexity. 


- name: My Play
  vars:
    ENVIRONMENT: '{{ environment}} '
    APP_NAME: '{{ app }}'
  tasks:  
    - name: 'My Play - Variable defination and validation'
      block: 
        - name: downaloading Environment data file and setting data into variable
          set_fact:
             my_json_data: "somehow get the data"  
        - name: "Read data from JSON"
          set_fact:
             key_name: "{{ my_json_data[ENVIRONMENT][APP_NAME].key }}"
             value: "{{ my_json_data[ENVIRONMENT][APP_NAME].value}}"
        - name: Print
          debug:
            msg: '{{key_name}} --- {{ value }}'

We see that to fetch information from JSON file we have to mention "my_json_data" which itself is a variable. If we try to concatenate the variable, it gets converted into a string and cannot be used, to fetch data from JSON. 

The best way to solve this problem is {{ my_json_data[ENVIRONMENT][APP_NAME].key }}


Comments

Popular posts from this blog

Caused by: java.sql.SQLTimeoutException: ORA-01013: user requested cancel of current operation

HashiCorp Vault Integration with Ansible Etower using approle

utility to extract date from text with java