Alexandr Kurilin
Alexandr Kurilin

Reputation: 7845

Ansible: are variables for specific role and inventory possible?

Let's say I have a nginx config file created from a template, which I use to configure certain hosts to redirect a server name from http to https:

server {
  listen                80;
  server_name           {{ server_name }};
  rewrite               ^ https://$server_name$request_uri? permanent;
}

Say I have two web sites hosted on the same machine:

each has its own server name and each needs the redirection above. At the same time let's say I have at least two separate deployment configurations, each represented by its own inventory file and its group_vars/ folder, for example:

each using a different server name. So now I have 2*2 = 4 separate server names:

I can't figure out how to define all of those 4 variables. I can't define two separate variables under group_vars/ because the j2 template expects only one variable name {{server_name}}, so I'd have to define the same template twice to make that work.

The other option is to have sitea and siteb as two separate roles (which I was going to do anyway), and store sever_name in roles/sitea/vars/main.yml, however that setup does not take inventory in consideration, meaning that I'd be down to 2 variables rather than 4.

Is this possible at all without template duplication or is Ansible not supporting this kind of scenario just yet?

Upvotes: 1

Views: 1990

Answers (2)

hkariti
hkariti

Reputation: 1719

If you're gonna separate them to two roles anyway, define the site names in inventory and pass them as role parameters:

    roles:
       - { role: sitea, server_name: "{{ sitea_server_name }}" }
       - { role: siteb, server_name: "{{ siteb_server_name }}" }

Upvotes: 1

Yuichiro
Yuichiro

Reputation: 1220

How about trying this. This may not be the answer you would expect.

:nginx.j2

server {
  listen                80;
  server_name           {% for host in groups['all'] -%}
{% if hostvars[host]['ansible_eth0']['ipv4']['address'] == ansible_eth0['ipv4']['address'] %}
{{ hostvars[host]['inventory_hostname'] }} {% endif %}{% endfor %} ;
  rewrite               ^ https://$server_name$request_uri? permanent;
}

This template will check all hosts. If group_host ip address and current_host ip address is same , add inventory_hostname to nginx config file. Even if it is not this way, you can get inventory_hostoname in other groups or hosts by using hostvars.

Upvotes: 0

Related Questions