Reputation: 13
I'm trying to write an nginx template for a load balancer in Ansible. If I have 5 application servers, then upstream server line must be written 5 times, each time the binding port increments by 1. Like this:
upstream app_servers {
server 127.0.0.1:4000 fail_timeout=0;
server 127.0.0.1:4001 fail_timeout=0;
server 127.0.0.1:4002 fail_timeout=0;
server 127.0.0.1:4003 fail_timeout=0;
server 127.0.0.1:4004 fail_timeout=0;
}
I have the number of application servers as a variable. How can I write that kind of loop in ansible template? I found "with_indexed_items" in ansible docs but I'm not sure it fits this case.
Upvotes: 1
Views: 8061
Reputation: 60029
with_indexed_items
would only be useful if you want to create 5 different files. Since you need this in a single file which most probably is written through a template task you can loop over a range:
upstream app_servers {
{% for number in range(5) %}
server 127.0.0.1:400{{ number }} fail_timeout=0;
{% endfor %}
}
I have the number of application servers as a variable.
You can use that variable in the range definition above, range(your_variable)
Without improvements this obviously will only work until 9 or you will create ports above 40010.
Jinja loops also do have an index property (actually two, one starting at 0 and one starting at 1) If you'd somehow would need to loop over your application servers (e.g. loop over hosts in the app inventory group) you could use this index then.
upstream app_servers {
{% for something in whatever %}
server 127.0.0.1:400{{ loop.index0 }} fail_timeout=0;
{% endfor %}
}
Upvotes: 4
Reputation: 35149
You may probably want to user Jinja template
and add little logic in there to iterate over set of servers.
Take a look at :
ansible template module http://docs.ansible.com/ansible/template_module.html
Jinja for loop http://jinja.pocoo.org/docs/dev/templates/
Upvotes: 0