am trying to create my 1st jinja2 template that extracts a field from a json string as am trying to create DHCP reserveration file.
here is an example inventory feed.
I would like to select the value from the mac address to use as a value as jinja2 value for a field for the interface that matches the ansible host. which could be in any postion on the interfaces.
how would I go about it
"TEST": {
"ansible_host": "192.171.130.8",
"interfaces": [
{
"ip_addresses": [
{
"address": "192.171.130.8/32",
}
],
"mac_address": "C8-F1-13-78-9E-E7"
},
{
"ip_addresses": [
{
"address": "192.171.130.80/32",
}
],
"mac_address": "85-9F-76-AE-57-10"
}
],
}
so I would like to doe something like
{{ hostvars[host].interfaces.[ip_addresses.address = ansible_host].mac_address }}
but am not sure how to go about it.
2
Answers
This looks like a good candidate for the
json_query
filter. My first thought was that this should work:But that returns an empty list. The following is a bit more verbose, but produces the expected result:
In a playbook:
NB: Watch your quoting; you’ll note that here I’ve used the YAML folding quote operating (
>
) because the expression contains both double quotes and single quotes, so putting either of those around the outside would mean escaping quotes inside the expression.Running the above playbook produces:
Since you’ve got the desired address in a variable (
ansible_host
), you would write instead:Our expression returns a list containing a single dictionary. If you want the
mac_address
field, treat the result just like any other Ansible array variable:Create the dictionary from the MAC addresses and lists of IPs
gives
Get rid of the masks
gives
Now, test which list contains the IP
gives the expected result
Example of a complete project for testing