Accessing an environment variable across nginx w/ Lua and Rails

Flambino asked:

I’m implementing something like this to let one service allow access to separate upstream service in nginx.

Briefly: A Rails app sets an HMAC cookie, which is then checked by some Lua code thanks to an access_by_lua directive in nginx.

To generate and verify the cookie, both Rails and nginx-Lua must of course share a secret key. I’ve tried setting this up as an environment variable in /etc/environment.

To make the var available in Rails, I had to fiddle with Unicorn’s init script a bit. But at least that script is contained within the project, and just symlinked into place.

Meanwhile, to get at the variable in Lua, I do something like this: os.getenv("MY_HMAC_SECRET"). But in order for Lua to have access to that when running under nginx, it must first be listed using the env directive in the main nginx config.

So now, I’m feeling like my configuration is being spread out all over the place:

  1. in /etc/environment (outside my project)
  2. in /etc/nginx/nginx.conf (outside my project)
  3. in unicorn’s init script
  4. in my site’s nginx vhost config

It’s starting to seem a little ridiculous just to make a simple string accessible in multiple places…

Is there a simpler way to do this? Honestly, the easiest way I can think of is hardcode it in the 2 places I need it, and be done. But that sounds nasty.

I answered:

Better to put it only in the two places it’s actually needed, in the two respective configuration files, than in the global environment where every process has access to it, as you have it now.

View the full question and answer on Server Fault.

Creative Commons License
This work is licensed under a Creative Commons Attribution-ShareAlike 3.0 Unported License.