Ansible loop - how to match up template values with with_items?

gkrizek picture gkrizek · Mar 17, 2017 · Viewed 10.5k times · Source

I'm trying to create files that have values that match their with_items values.

I have a var list like so:

 sites:
   - domain: google.com
     cname: blue
   - domain: facebook.com
     cname: green
   - domain: twitter.com
     cname: red

I create individual files for each of the objects in the list in this task:

- name: Create files
  template:
    src: file.conf
    dest: "/etc/nginx/conf.d/{{item.cname}}.conf"
  with_items: "{{sites}}"

These both work great. What do I need to have in my template file for it create a file called blue.conf and has google.com in it only.

I have tried a lot of variations. The closest I got to was this:

   server {
        listen 80;
        listen [::]:80;
      {% for item in sites %}
        server_name  {{item.cname}}.es.nodesource.io;

        location / {
          proxy_pass {{item.domain}};
        }
      {% endfor %}
    }

That will create individual files, but every file has all the domains and cnames.

Answer

techraf picture techraf · Mar 17, 2017

You already have the variable item defined and passed to the template, so there is no need to loop again.

Try:

server {
    listen 80;
    listen [::]:80;
    server_name  {{item.cname}}.es.nodesource.io;

    location / {
      proxy_pass {{item.domain}};
    }
}