Consul template is a wonderful tool that allows you to create configuration templates while interpolating consul resources and many important variables. You can also use these templates to automatically change the contents of your configuration files using the watch
class in puppet.
To set up an nginx proxy using consul-template to control configuration, what you can do is initialize nginx using the puppet-nginx
module and change the config files using consul template.
Here is the full code for reference. This is just what it should roughly look like, and I haven’t tested this, so please read it and just take whichever parts you need to make it work.
1 |
|
1 |
|
Let’s go by the parts one by one.
1 |
|
In this part, we just initialize file paths for our config files:
- The path for the consul template configuration
- The file for the nginx config, which we will use as target when we run
consul-template
. In this case our server is named_
, but you can change this to whatever you prefer.
1 |
|
Here, we create a “watch” from the consul template to the target nginx file. The command
attribute is ran every time a change is detected. So, every time the config changes, we trigger an nginx reload
.
1 |
|
Here, we execute consul-template once to trigger the watch for the first time. If the config file already exists, it means that the nginx config has already been created and is being watched, so we don’t have to run consul-template
anymore.
1 |
|
This includes the nginx module, which sets up the nginx service and whatnot.
Let’s head over to the template for the nginx server.
1 |
|
In here, the server is just initialized and is listening at port 80. I had to use 8.8.8.8
as a resolver, but you can remove this part if you don’t need it. The file paths for access_log
and error_log
can also be changed to your liking.
1 |
|
In here, we are telling nginx to forward requests from the root path to http://www.sample_website.com
plus the value of the key foo
in your consul KV. If this value changes, then new requests are routed to the new URI. Consul template will then restart on its own.