diff --git a/apisix/cli/file.lua b/apisix/cli/file.lua index b4d51fb2e792..5d066e0dadcd 100644 --- a/apisix/cli/file.lua +++ b/apisix/cli/file.lua @@ -65,8 +65,16 @@ local function resolve_conf_var(conf) local var_used = false -- we use '${{var}}' because '$var' and '${var}' are taken -- by Nginx - local new_val = val:gsub("%$%{%{%s*([%w_]+)%s*%}%}", function(var) - local v = getenv(var) + local new_val = val:gsub("%$%{%{%s*([%w_]+[%:%=]?.-)%s*%}%}", function(var) + local i, j = var:find("%:%=") + local default + if i and j then + default = var:sub(i + 2, #var) + default = default:gsub('^%s*(.-)%s*$', '%1') + var = var:sub(1, i - 1) + end + + local v = getenv(var) or default if v then if not exported_vars then exported_vars = {} diff --git a/conf/config.yaml b/conf/config.yaml index b45fa5e513d8..421ac0912aa6 100644 --- a/conf/config.yaml +++ b/conf/config.yaml @@ -30,6 +30,16 @@ # And then run `export ETCD_HOST=$your_host` before `make init`. # # If the configured environment variable can't be found, an error will be thrown. +# +# Also, If you want to use default value when the environment variable not set, +# Use `${{VAR:=default_value}}` instead. For instance: +# +# etcd: +# host: +# - http://${{ETCD_HOST:=localhost}}:2379 +# +# This will find environment variable `ETCD_HOST` first, and if it's not exist it will use `localhost` as default value. +# apisix: admin_key: - name: admin diff --git a/t/cli/test_main.sh b/t/cli/test_main.sh index 771d96846d13..f9c6a386e8b0 100755 --- a/t/cli/test_main.sh +++ b/t/cli/test_main.sh @@ -310,6 +310,45 @@ fi echo "pass: support environment variables in local_conf" +# support default value when environment not set +echo ' +tests: + key: ${{TEST_ENV:=1.1.1.1}} +' > conf/config.yaml + +make init + +if ! grep "env TEST_ENV=1.1.1.1;" conf/nginx.conf > /dev/null; then + echo "failed: should use default value when environment not set" + exit 1 +fi + +echo ' +tests: + key: ${{TEST_ENV:=very-long-domain-with-many-symbols.absolutely-non-exists-123ss.com:1234/path?param1=value1}} +' > conf/config.yaml + +make init + +if ! grep "env TEST_ENV=very-long-domain-with-many-symbols.absolutely-non-exists-123ss.com:1234/path?param1=value1;" conf/nginx.conf > /dev/null; then + echo "failed: should use default value when environment not set" + exit 1 +fi + +echo ' +tests: + key: ${{TEST_ENV:=192.168.1.1}} +' > conf/config.yaml + +TEST_ENV=127.0.0.1 make init + +if ! grep "env TEST_ENV=127.0.0.1;" conf/nginx.conf > /dev/null; then + echo "failed: should use environment variable when environment is set" + exit 1 +fi + +echo "pass: support default value when environment not set" + # support merging worker_processes echo ' nginx_config: