railsuser400
railsuser400

Reputation: 1023

ansible nginx server_name values

I've got the following ansible hosts file:

[production]
255.255.255.1
255.255.255.2
255.255.255.3

My inventory file has an nginx role that has a config template file that gets copied to the nginx directory on the servers during the setup deploy. At the moment part of this config file looks like this:

...

server {
  listen 80;
  server_name 255.255.255.1;
  root /path/to/public;

  ...
}

...

The server_name directive points to one of the IP addresses from the hosts file. How can I change it so that it will point to the correct production server IP for each server that it deploys to?

Additionally, if all n hosts will be pointing to the same domain, is it a better idea to have the server_name directive's value be that domain instead of the IP addresses?

Upvotes: 1

Views: 1774

Answers (1)

Charlie O.
Charlie O.

Reputation: 481

If you want to get the IP of the server you're currently deploying the template to, you'll need to convert your Nginx config to a Jinja template. Place it in your roles/nginx/templates directory and edit it to use the appropriate facts -

server {
  listen 80;
  server_name {{ ansible_eth0.ipv4.address }};
  root /path/to/public;

  ...
}

Inside your Playbook adjust the task to call a template -

- name: deliver nginx configuration to server
  template: src=site.j2 dest=/etc/nginx/sites-available/site

If you want to use a server name you'll need to define that somewhere, most likely in your host_vars or hosts file. For example, using your host file above you could do something like this -

[production]
255.255.255.1
255.255.255.2
255.255.255.3

[production:vars]
server_name=www.example.com

Then simply replace the above template with {{ server_name }} instead of the Ansible fact and you should be good to go.

Upvotes: 4

Related Questions