Home > database >  How can I reference a variable set by lua in nginx?
How can I reference a variable set by lua in nginx?

Time:11-18

I am using nginx lua docker image firesh/nginx-lua:alpine-3.4. And i tried to use environment variable in nginx.config file. Below is the configuration in /etc/nginx/nginx.conf.

 user nginx;
    env ES_USERNAME;
    env ES_PWD;
    worker_processes  1;
    events {
      worker_connections  10240;
    }

    http {
      server {
          listen       8080;
          server_name  localhost;
          set_by_lua $es_username os.getenv("ES_USERNAME");
          set_by_lua $es_pwd os.getenv("ES_PWD");
          
          location /health {
            proxy_pass  http://$es_username:$es_pwd@elk-es-http:9200/_cluster/health;
          }
...

After launching the container, I see this error in the log:

2021/11/18 01:07:14 [error] 6#6: *6 failed to load inlined Lua code: set_by_lua:1: unexpected symbol near '"http://"', client: 10.0.4.122, server: localhost, request: "GET /health HTTP/1.1", host: "10.0.2.170:8080"

The problem is that the url after proxy_pass is not reading the variable from lua. It treats the ${es_username} as a string rather than read its value. What is the correct way to use that?

CodePudding user response:

That sounds strange. I rather expect both $es_username and $es_pwd variables will have an empty value. set_by_lua expects a function that should return a value, and your returns nothing. The correct usage is

set_by_lua $es_username 'return os.getenv("ES_USERNAME")';
set_by_lua $es_pwd      'return os.getenv("ES_PWD")';
  • Related