Reputation: 5413
I am a writing a template file for virtual host and DNS inside the file should change as per environment host-name.Below is problem i am trying to solve:
server {
listen 80;
charset utf-8;
server_name "{{ 'a.com if ansible_hostname='p.com' 'b.com' if ansible_hostname= 'd.com' 'z.com' if ansible hostname is 'k.com' else 'default.com' }}";
rewrite ^(.*) https://$server_name$1 permanent;
}
How can i achieve this thing in template ie:
{{ 'a.com' if ansible_hostname='p.com' 'b.com' if ansible_hostname= 'd.com' 'z.com' if ansible hostname is 'k.com' else 'default.com' }}" `
I am new to jinja 2 and have no idea how to do this. Single if else statement is working but how can i use multiple if else statement for defining the value of a variable in the file.
Upvotes: 4
Views: 7357
Reputation: 59989
I think no Jinja filter will be of use here but you can simply do it with a dict:
server {
listen 80;
charset utf-8;
server_name {{ {"a.com": "b.com", "c.com": "d.com"}[ansible_hostname] | default("default.com") }};
rewrite ^(.*) https://$server_name$1 permanent;
}
That might work with 2 or a few more hosts but gets quickly dirty with increasing numbers. In general I think it would be more clean if such decisions would not happen in a template file. This could as well be a config option in either host_vars or group_vars. To stay with your example hosts you could have a file host_vars/a.com
with the content
---
server: b.com
...
and a file host_vars/c.com
with the content
---
server: d.com
...
In a file group_vars/all
you can define the default value.
---
server: default.com
...
Upvotes: 2
Reputation: 5413
So after some research work i was able to crack down the issue.We can
{% if ansible_hostname == 'a.com' %}
{% set server = 'b.com' %}
{% elif ansible_hostname == 'c.com' %}
{% set server = 'd.com' %}
{% else %}
{% set server = 'define yourself' %}
{% endif %}
server {
listen 80;
charset utf-8;
server_name {{ server }};
rewrite ^(.*) https://$server_name$1 permanent;
}
Still if someone can show the use of jinja2 filters for achieving this then that will be much appreciated.
Upvotes: 3