如何在 nginx 中引用 lua 设置的变量?

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

我正在使用 nginx lua docker 图片 firesh/nginx-lua:alpine-3.4。我尝试在 nginx.config 文件中使用环境变量。下面是/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;
          }
...

启动容器后,我在日志中看到这个错误:

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"

问题是 proxy_pass 之后的 url 没有从 lua 读取变量。它将 ${es_username} 视为字符串而不是读取其值。正确的使用方法是什么?

这听起来很奇怪。我更希望 $es_username$es_pwd 变量都具有空值。 set_by_lua 期望一个函数应该 return 一个值,而你的 return 什么都没有。正确的用法是

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