I have a YAML file with variables that I would like to use in an Ansible template. The file looks like this:
---
config:
version: "4.0"
description: "Global configuration"
sites:
- name: "Site J"
description: "Ficititious Site J"
servers:
- hostname: server1
- hostname: server2
- hostname: server3
- name: "Site K"
description: "Ficititious Site K"
- name: "Site L"
description: "Ficititious Site L"
I'd trying to reference the servers, but, for the life of me can't figure out the syntax in a Jinja2 template. Here's my current template:
{{ config | to_nice_json }}
{% for site in config['sites'] %}
{{ site['name'] }}
{{ site['description'] }}
{% endfor %}
And the output is:
{
"description": "Global configuration",
"sites": [
{
"description": "Ficititious Site J",
"name": "Site J",
"servers": [
{
"hostname": "server1"
},
{
"hostname": "server2"
},
{
"hostname": "server3"
}
]
},
{
"description": "Ficititious Site K",
"name": "Site K"
},
{
"description": "Ficititious Site L",
"name": "Site L"
}
],
"version": "4.0"
}
Site J
Ficititious Site J
Site K
Ficititious Site K
Site L
Ficititious Site L
My problem is accessing the data under "servers:" within the existing site loop. The most obvious syntax for a nested loop:
{% for server in site['servers'] %}
{{ server['hostname'] }}
{% endfor %}
doesn't work. I get this Ansible error:
fatal: [localhost] => {'msg': "AnsibleUndefinedVariable: One or more undefined variables: 'dict' object has no attribute 'servers'", 'failed': True}
What's the correct syntax for looping through the servers in the YAML file under each of the sites? I've tried many variations and can't seem to find the right one.