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

我正在使用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}视为字符串而不是读取其值。正确的使用方式是什么?

原文链接 https://stackoverflow.com/questions/70013351

点赞
stackoverflow用户7121513
stackoverflow用户7121513

这听起来很奇怪。我认为 $es_username$es_pwd 两个变量都应该有空值。set_by_lua 函数期待返回一个值的函数,而你的函数没有返回任何内容。正确的用法是:

set_by_lua $es_username 'return os.getenv("ES_USERNAME")';
set_by_lua $es_pwd      'return os.getenv("ES_PWD")';
2021-11-18 01:10:09