Allow the usen of the "env" directive in contexts other than "main"

Maxim Dounin mdounin at mdounin.ru
Fri Jan 5 05:55:25 UTC 2018


Hello!

On Fri, Jan 05, 2018 at 02:28:45AM +0000, German Jaber wrote:

> What I want to be able to do is basically what this guy tried to do:
> https://serverfault.com/questions/577370/how-can-i-use-environment-variables-in-nginx-conf
> 
> Succinctly, I want to pass the value of environment variables to my server
> and location contexts, and use those values in the arguments passed to my
> directives.
> 
> For example. Say I have two servers, dev and prod; and that I have a file
> in sites-enabled that reads:
> 
> env URL;
> server {
>     listen 80;
>     server_name $URL;
> 
>     access_log /var/log/nginx/access.log;
>     error_log /var/log/nginx/error.log;
> 
>     location /static/ {
>         alias /app/static/;
>     }
> 
>     location / {
>         alias /app/main/;
>     }
> }
> 
> I want the server_name directive to receive as argument the domains (or
> list of domains) contained in the environment variable $URL.
> 
> This is very useful when using container technology (Docker, Kubernetes,
> etc) as the same Nginx configuration files may be used by many different
> environments (dev, staging, prod, CI, CD, etc). Many times these
> environments are created dynamically and programmatically by our
> continuous delivery pipelines, so setting them by hand is cumbersome or
> downright impossible. Right now I use sed and/or envsubst in our scripts to
> modify the file before using it.
> 
> It would simplify our deployment scripts a ton if Nginx could just read
> these environment variables and substitute them for us wherever we need.

So, this is certainly not about allowing the "env" directive 
in other contexts, but instead using environment variables in the 
configuration.  This is not something nginx currently supports, 
but rather a completely new mechanism - some preprocessing of the 
configuration.

Something like this was discussed more than once, and the current 
consensus is that using various template mechanisms like sed, cpp, 
or whatever you prefer to is a good enough solution for such 
tasks.

Note that using variables as you seem to imply in the example 
above is a bad idea, as variables are evaluated at run-time.  
See http://nginx.org/en/docs/faq/variables_in_config.html for 
details.

-- 
Maxim Dounin
http://mdounin.ru/


More information about the nginx mailing list