简体   繁体   中英

Setting NGINX (OpenResty) variables using Lua to Read from File

Is it possible with Lua to set an NGINX variable within a location block to a value read from a file?

I'm working with an NGINX container, deployed within a kubernetes pod. I have a value that is set in a file rather than an environment variable

eg

set   $a_key    <a_value_from_file_set_here>;

I have attempted to do something similar to this:

  set_by_lua_block $a_key {
    file = io.open('/tmp/string.txt', 'r')
    local data = file:read()
    io.close(file)
    return data
  }

The above caused a 500 error and was based on the example here https://onelinerhub.com/nginx-lua/how-to-read-file-with-lua

I haven't been able to get this working so far. I'm wondering if it's even possible or desirable. I know I can configure NGINX if I set the value as an environment variable using envsubst. My reason for looking into achieving the same with Lua is because this will avoid having to override the docker entrypoint with shell commands which has some advantages in terms of decluttering the Kubernetes code

You need to provide the complete path to the directory where the file is located. For example, if you are copying this text file to the same folder as your Lua files, you will use

local file = io.open('/usr/local/openresty/nginx/string.txt', 'r')

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM