Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Env var substitution #125

Merged
merged 1 commit into from
Aug 23, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
28 changes: 28 additions & 0 deletions pkg/config/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ import (
"fmt"
"io/ioutil"
"net/url"
"os"
"path/filepath"
"regexp"
"strconv"
Expand Down Expand Up @@ -64,6 +65,12 @@ func LoadFile(filename string, logger log.Logger) (*Config, []byte, error) {
if err != nil {
return nil, nil, err
}

content, err = substituteEnvVars(content, logger)
if err != nil {
return nil, nil, err
}

cfg, err := Load(string(content))
if err != nil {
return nil, nil, err
Expand All @@ -73,6 +80,27 @@ func LoadFile(filename string, logger log.Logger) (*Config, []byte, error) {
return cfg, content, nil
}

// expand env variables $(var) from the config file
// taken from https://github.dev/thanos-io/thanos/blob/296c4ab4baf2c8dd6abdf2649b0660ac77505e63/pkg/reloader/reloader.go#L445-L462 by https://github.com/fabxc
func substituteEnvVars(b []byte, logger log.Logger) (r []byte, err error) {
rati3l marked this conversation as resolved.
Show resolved Hide resolved
var envRe = regexp.MustCompile(`\$\(([a-zA-Z_0-9]+)\)`)
r = envRe.ReplaceAllFunc(b, func(n []byte) []byte {
if err != nil {
return nil
}

n = n[2 : len(n)-1]

v, ok := os.LookupEnv(string(n))
if !ok {
err = fmt.Errorf("Missing env variable: %q", n)
return nil
}
return []byte(v)
})
return r, err
}

// resolveFilepaths joins all relative paths in a configuration
// with a given base directory.
func resolveFilepaths(baseDir string, cfg *Config, logger log.Logger) {
Expand Down
17 changes: 17 additions & 0 deletions pkg/config/config_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -93,6 +93,23 @@ func TestLoadFile(t *testing.T) {

}

// Checks if the env var substitution is happening correctly in the loaded file
func TestEnvSubstitution(t *testing.T) {

config := "user: $(JA_USER)"
os.Setenv("JA_USER", "user")

content, err := substituteEnvVars([]byte(config), log.NewNopLogger())
expected := "user: user"
require.NoError(t, err)
require.Equal(t, string(content), expected)

config = "user: $(JA_MISSING)"
_, err = substituteEnvVars([]byte(config), log.NewNopLogger())
require.Error(t, err)

}

// A test version of the ReceiverConfig struct to create test yaml fixtures.
type receiverTestConfig struct {
Name string `yaml:"name,omitempty"`
Expand Down