Unable to use environment variables in Lua code
Asked Answered
R

1

23

I have some Lua code, which I use in my openresty nginx.conf file. This Lua code contains such lines:

...
local secret = os.getenv("PATH")
assert(secret ~= nil, "Environment variable PATH not set")
...

Just for testing reasons I tried to check if PATH variable is set and for some reason the assert statement does not pass. I see in the console:

Environment variable PATH not set

However, when I run this

$ echo $PATH

I see, that this variable indeed has some value. So, what is wrong with that and how can I fix it?

Rattlehead answered 23/1, 2017 at 5:58 Comment(0)
S
26

You need to tell nginx to make environment variables available. From the docs for the env directive: "By default, nginx removes all environment variables inherited from its parent process except the TZ variable. This directive allows preserving some of the inherited variables, changing their values, or creating new environment variables."

So, in your case you'd need to specify env PATH; in nginx.conf.

Spieler answered 23/1, 2017 at 6:46 Comment(7)
@Jacobian, you may want to accept the answer if it worked for you.Spieler
Yes, sure! Thank you, sir!Rattlehead
"you'd need to specify env PATH; in nginx.conf". Can you please show example? Should I also specify a path? or just add "env PATH" ? Thanks.Nahuatl
Right; that's the entire command you need to add to nginx.conf.Spieler
@PaulKulchenko Hi, I had the same issue. I defined a new env var "export SECRET=mySecret" and inside nginx.conf I specify env SECRET; but when calling it, it seems like nothing exists. Only if I specify an env var that already existed, calling it will print back the right value. I opened a thread please take a look if you can: #66519218Nahuatl
@PaulKulchenko Hi man your advise is really needed as this situation is critical. Thanks a lot.Nahuatl
You need to make sure you're setting up the environment variable that nginx can see; there is nothing else you may need to do (other than what's written in the answer).Spieler

© 2022 - 2024 — McMap. All rights reserved.