'extract data with json_query from jinja2 variable in ansible

I have a variable in the inventory that contains a JSON formatted data.

I want to extract a specific part of the data with json_query.

The variable contains a list of domains with related IP addresses (the JSON is valid):

DOMAIN={"domain1.net": {"addr": ["10.10.10.10", "10.10.10.20"]}, "domain2.net": {"addr": ["172.16.10.1", "172.16.20.1", "172.16.30.1"]}}

With an ansible-playbook, using json_query, I want to extact only the domain2.net IP addresses.

I've used https://api.gopipeline.io/jmespath-tester to validate the JMESPath query.

With this filter: "domain2.net".addr in the jmespath-tester, I got the following (expected) output:

[
  "172.16.10.1",
  "172.16.20.1",
  "172.16.30.1"
]

When I apply the same json_query with this ansible-playbook, I have no output:

Task

 ---                                                                                      
 - name: Extract addr for domain2.net              
   tags: test                                                                            
   debug: msg="{{ DOMAIN | to_json | from_json | json_query("domain2.net".addr) }}"

Output:

ok: [domain-lab-1] => {
    "msg": ""
}

I've tested also another query, by filtering only domain2.net in JMESPath online tester: https://api.gopipeline.io/jmespath-tester and I get this expected output:

{
  "addr": [
    "172.16.10.1",
    "172.16.20.1",
    "172.16.30.1"
  ]
}

But, when I try to do the same within an Ansible playbook, still no output: Task

 ---                                                                                      
 - name: Extract addr for domain2.net              
   tags: test                                                                            
   debug: msg="{{ DOMAIN | to_json | from_json | json_query("domain2.net") }}"

Output:

ok: [domain-lab-1] => {
    "msg": ""
}

If I try to print only the DOMAIN var, I can see the whole JSON output.
So, the variable is correctly read.

I'm using ansible 2.9.14.

I've read that the to json|from json from here:

Ansible : filter elements containing string with JMESPath

I'm not sure if is needed in my case, anyway adding or removing them does not make any difference.



Sources

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

Source: Stack Overflow

Solution Source