nginxnginx-configopenresty

How to set initial value for variable in Openresty


  1. What I want

I am using openresty stream, I want to set an variable in nginx.conf, and lua file can visit this variable.

  1. What have I tried

I have tried lua_add_variable, but it seems that lua_add_variable can not set initial value.

I also tried set $var value, but I got error:"set" directive is not allowed here , I think set can not be used in stream

  1. my codes

     nginx.conf
    
     stream {
         # lua_add_variable $servers_list "client1;client2";
         # set $servers_list "client1;client2"; # set not allowed here
    
         upstream backend {
             server 127.0.0.1:666;
         }
         server {
             lua_code_cache off;
             listen 65;
             preread_by_lua_file lua/echo.lua;
             content_by_lua_block {
                 ngx.say("nerver reach here")
             }
         }
    
    }
    
    echo.lua
    
    ngx.log(ngx.ERR, "list is ", ngx.var.servers_list) -- I want to get "client1;client2" here
    

Solution

  • The set directive is available for the stream subsystem — https://nginx.org/en/docs/stream/ngx_stream_set_module.html#set — but in the server context block only:

    Context: server

    To fix the following error:

    "set" directive is not allowed here

    move the directive to the server context block:

    server {
        set $servers_list "client1;client2";
        lua_code_cache off;
        ...