Skip to content

Commit

Permalink
feat: support environment variable substitution in config files
Browse files Browse the repository at this point in the history
Signed-off-by: Marin Bezhanov <marin.bezhanov@gmail.com>
  • Loading branch information
mbezhanov committed Jun 19, 2024
1 parent fee220d commit 2fab1f5
Show file tree
Hide file tree
Showing 3 changed files with 41 additions and 1 deletion.
24 changes: 23 additions & 1 deletion internal/config/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ import (
"os"
"path/filepath"
"reflect"
"regexp"
"slices"
"strings"
"time"
Expand All @@ -27,10 +28,12 @@ const (
)

var (
_ validator = (*Config)(nil)
_ validator = (*Config)(nil)
envsubst = regexp.MustCompile(`^\${([a-zA-Z_]+[a-zA-Z0-9_]*)}$`)
)

var DecodeHooks = []mapstructure.DecodeHookFunc{
stringToEnvsubstHookFunc(),
mapstructure.StringToTimeDurationHookFunc(),
stringToSliceHookFunc(),
stringToEnumHookFunc(stringToCacheBackend),
Expand Down Expand Up @@ -475,6 +478,25 @@ func experimentalFieldSkipHookFunc(types ...reflect.Type) mapstructure.DecodeHoo
}
}

// stringToEnvsubstHookFunc returns a DecodeHookFunc that substitutes
// `${VARIABLE}` strings with their matching environment variables.
func stringToEnvsubstHookFunc() mapstructure.DecodeHookFunc {
return func(
f reflect.Type,
t reflect.Type,
data interface{}) (interface{}, error) {
if f.Kind() != reflect.String || f != reflect.TypeOf("") {
return data, nil
}
str := data.(string)
if !envsubst.MatchString(str) {
return data, nil
}
key := envsubst.ReplaceAllString(str, `$1`)
return os.Getenv(key), nil
}
}

// stringToSliceHookFunc returns a DecodeHookFunc that converts
// string to []string by splitting using strings.Fields().
func stringToSliceHookFunc() mapstructure.DecodeHookFunc {
Expand Down
14 changes: 14 additions & 0 deletions internal/config/config_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -243,6 +243,20 @@ func TestLoad(t *testing.T) {
return cfg
},
},
{
name: "environment variable substitution",
path: "./testdata/envsubst.yml",
envOverrides: map[string]string{
"HTTP_PORT": "18080",
"LOG_FORMAT": "json",
},
expected: func() *Config {
cfg := Default()
cfg.Log.Encoding = "json"
cfg.Server.HTTPPort = 18080
return cfg
},
},
{
name: "deprecated tracing jaeger",
path: "./testdata/deprecated/tracing_jaeger.yml",
Expand Down
4 changes: 4 additions & 0 deletions internal/config/testdata/envsubst.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
server:
http_port: ${HTTP_PORT}
log:
encoding: ${LOG_FORMAT}

0 comments on commit 2fab1f5

Please sign in to comment.