Using system environment variables in a Lua project can be confusing when it runs inside Kong or OpenResty. A common assumption is that os.getenv() should work directly, but in practice it does not.
The reason is in the stack underneath: Kong is built on OpenResty, and OpenResty runs on Nginx. When Nginx starts, it clears almost all environment variables inherited from the parent process. According to the Nginx documentation, the default behavior is:
By default, nginx removes all environment variables inherited from its parent process except the TZ variable.
Because of that, calling os.getenv() from Lua will not return the variables you expect unless those variables have been explicitly exposed to Nginx.
Making environment variables available in OpenResty
To use environment variables in Lua under OpenResty, you need to declare them in nginx.conf first. Add the variables you want to keep with the env directive, for example:
events{ ... }
env PATH;
env USERNAME;
After updating the configuration, restart Nginx. Once it comes back up, your Lua code can read the value with os.getenv("USERNAME").
Using os.getenv() inside a Kong plugin
The same rule applies when your Lua code runs inside a Kong plugin. The difference is that Kong manages its own generated Nginx configuration, so editing that generated file directly is not a workable solution. Even if you change it manually, Kong will regenerate it and overwrite your changes.
The practical way to handle this is to use Kong’s custom Nginx configuration support.
Create a file named custom-nginx.conf, and declare the environment variables there in the same way:
events{ ... }
env PATH;
env USERNAME;
Then restart Kong and point it to that custom Nginx configuration. Be careful with the command-line options here: -c is for Kong’s own configuration file, while --nginx-conf is the option for the custom Nginx template configuration.
kong restart -c kong.conf --nginx-conf custom-nginx.conf
After Kong restarts successfully, your plugin code can use os.getenv("USERNAME") to read the environment variable normally.