title: Ansible Nested Loop in Template
body: <p>I have a YAML file with variables that I would like to use in an Ansible template. The file looks like this:</p>
  
  <pre><code>---
  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"
  </code></pre>
  
  <p>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:</p>
  
  <pre><code>{{ config | to_nice_json }}
  
  {% for site in config['sites'] %}
  {{ site['name'] }}
  {{ site['description'] }}
  
  {% endfor %}
  </code></pre>
  
  <p>And the output is:</p>
  
  <pre><code>{
      "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
  </code></pre>
  
  <p>My problem is accessing the data under "servers:" within the existing site loop. The most obvious syntax for a nested loop:</p>
  
  <pre><code>{% for server in site['servers'] %}
  {{ server['hostname'] }}
  {% endfor %}
  </code></pre>
  
  <p>doesn't work. I get this Ansible error:</p>
  
  <pre><code>fatal: [localhost] =&gt; {'msg': "AnsibleUndefinedVariable: One or more undefined variables: 'dict' object has no attribute 'servers'", 'failed': True}
  </code></pre>
  
  <p>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.</p>