Skip to content

Instantly share code, notes, and snippets.

@runlevel5
Last active February 28, 2024 09:17
Show Gist options
  • Star 6 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save runlevel5/5d038e91ea1f874a1dd1608d4e7fcace to your computer and use it in GitHub Desktop.
Save runlevel5/5d038e91ea1f874a1dd1608d4e7fcace to your computer and use it in GitHub Desktop.
Using njs to fetch environment variables

There are many ways to parse in variable into the nginx config file. Some uses set_by_lua which is offered by lua-nginx-module. Some use envstubst to populate varilabes into a template file.

Today I am going to show you how to do that with njs the JS scripting engine for nginx.

## /etc/nginx/fetch_env.js
function fetch_upstream_host(r) {
  return process.env.UPSTREAM_HOST;
}

function fetch_upstream_port(r) {
  return process.env.UPSTREAM_PORT;
}
## /etc/nginx/nginx.conf
load_module modules/ngx_http_js_module.so;

env UPSTREAM_HOST;
env UPSTREAM_PORT;

http {
  js_include fetch_env.js;
  js_set $upstream_host fetch_upstream_host;
  js_set $upstream_port fetch_upstream_port;

  server {
    # ....

    location / {
      # ....

      proxy_pass http://$upstream_host:$upstream_port;
    }
  }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment