'how to put double quotes key as varaible in json query

I need to put double-quoted key as variable in JSON query. It works fine if I put key string directly with backslash, But doesn't when I used it as variable

---
- hosts: localhost
  gather_facts: no
  vars:
    cert: |
      {
        "apiVersion": "v1",
        "data": {
            "ca.crt": "xxxx",
            "tls.crt": "yyyyy",
            "tls.key": "zzzzz"
        }
 
      }
    cert_type: "ca.crt"
  tasks:
    - debug:
        #msg: "{{cert|from_json|json_query('data.`{{cert_type}}`')}}"  ## Does not work 
        msg: "{{cert|from_json|json_query('data.\"ca.crt\"')}}"   ## works


Solution 1:[1]

You never nest Jinja {{...}} template markers. When you write this:

msg: "{{cert|from_json|json_query('data.`{{cert_type}}`')}}"  ## Does not work 

You are looking for the literal string {{cert_type}}. You want to perform variable interpolation, which might look something like this (using Jinja's string concatenation operator):

    - debug:
        msg: >-
          {{cert|from_json|json_query('data."' ~ cert_type ~ '"') }}

Or this (using Python-style format method):

    - debug:
        msg: >-
          {{cert|from_json|json_query('data."{}"'.format(cert_type)) }}

Given your example playbook, both of the above tasks result in:

TASK [debug] ********************************************************************************************
ok: [localhost] => {
    "msg": "xxxx"
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 larsks