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

1

11

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.

Gombosi answered 17/3, 2017 at 0:56 Comment(1)
Similar: #31142869Stanza
P
19

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}};
    }
}
Protero answered 17/3, 2017 at 2:5 Comment(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.Gombosi

© 2022 - 2024 — McMap. All rights reserved.