skip to Main Content

I’m trying to use a variable in a variable.

I have one JSON variable :

os: { 

   "centos_7_5": {
    offer: "CentOS",
    publisher: "OpenLogic",
    sku: "7.5",
    version: "latest"
    },    
   "debian_9": {
    offer: "Debian",
    publisher: "credativ",
    sku: "9",
    version: "latest"
    }
}

If I use

  - debug:
      msg: " {{ os.debian_9.offer }}"

The output is as desired :

"msg": " Debian"

Now, I’m trying to put the OS name in a variable (so that the variable can be in a config file) as follows :

desired_os: debian_9

I would like to do something like this :

- debug:
    msg: " {{ os.desired_os.offer }}"

But I can’t find a way to make it work.
I tried some concatenation in a set_fact using '{{ "os."~desired_os~".offer" }}' but the output is not as desired :

"msg": "stuff.os.debian_9.offer"

Thanks.

4

Answers


  1. Hi try use this snippet:

    json

    {
        "os": {
            "centos_7_5": {
                "offer": "CentOS",
                "publisher": "OpenLogic",
                "sku": "7.5",
                "version": "latest"
            },
            "debian_9": {
                "offer": "Debian",
                "publisher": "credativ",
                "sku": "9",
                "version": "latest"
            }
        }
    }
    

    playbook:

    ---
    
    - hosts: all
      gather_facts: False
      vars:
        jsonVar: "{{ lookup('file', 'j.json') | from_json }}"
        dist: "debian_9"
    
      tasks:
    
        - name: test loop
          debug: msg="{{ jsonVar['os'][dist] }}"
    
    Login or Signup to reply.
  2. You can use the varname[var] notation.

    - hosts: localhost
      gather_facts: no
    
      vars:
        os: { 
       "centos_7_5": {
        offer: "CentOS",
        publisher: "OpenLogic",
        sku: "7.5",
        version: "latest"
        },    
       "debian_9": {
        offer: "Debian",
        publisher: "credativ",
        sku: "9",
        version: "latest"
        }
        }
        desired_os: debian_9
    
      tasks:
        - debug:
            msg: " {{ os['debian_9'].offer }}"
        - debug:
            msg: " {{ os[desired_os].offer }}"
    
    Login or Signup to reply.
  3. Simply add the variable within double brackets.

    - debug:
         msg: " {{ os.{{ desired_os }}.offer }}"
    
    Login or Signup to reply.
  4. Please try as below

    debug: msg= "{{os.vars[desired_os].offer}}"
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search