10

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.

techraf
  • 64,883
  • 27
  • 193
  • 198
gkrizek
  • 978
  • 3
  • 10
  • 18
  • Similar: https://stackoverflow.com/questions/31142369/how-to-use-template-module-with-different-set-of-variables – Flux Feb 12 '19 at 14:19

1 Answers1

18

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}};
    }
}
techraf
  • 64,883
  • 27
  • 193
  • 198
  • 1
    Wow, I was way overthinking it. This works, thanks. I guess I was thinking that it got the template items from variables defined somewhere, not passed in from the task. – gkrizek Mar 17 '17 at 02:54