Skip to content

Commit bee385c

Browse files
committed
feat: Support environment variables for config settings
Enable Viper to work with environment variables. Kuberlr will honour environment variables with a name matching the key uppercased and prefixed with `KUBRERLR` (like `KUBERLR_ALLOWDOWNLOAD`) and use them for the config settings. These environment variables take precedence over the config file settings. Signed-off-by: Víctor Cuadrado Juan <[email protected]>
1 parent 280d9d9 commit bee385c

File tree

3 files changed

+41
-1
lines changed

3 files changed

+41
-1
lines changed

README.md

+4
Original file line numberDiff line numberDiff line change
@@ -131,3 +131,7 @@ Timeout = 1
131131
# Default "https://dl.k8s.io"
132132
KubeMirrorUrl = "https://dl.k8s.io"
133133
```
134+
135+
The behaviour can also be adjusted by using environment variables matching the
136+
config file: `KUBERLR_ALLOWDOWNLOAD`, `KUBERLR_SYSTEMPATH`, `KUBERLR_TIMEOUT`,
137+
`KUBERLR_KUBEMIRRORURL`, and so on.

internal/config/config.go

+6
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@ package config
22

33
import (
44
"os"
5+
"strings"
56

67
"github.com/spf13/viper"
78

@@ -34,6 +35,11 @@ func (c *Cfg) Load() (*viper.Viper, error) {
3435

3536
v.SetConfigType("toml")
3637

38+
// read environment variables, they take precedence
39+
v.AutomaticEnv()
40+
v.SetEnvPrefix("KUBERLR")
41+
v.SetEnvKeyReplacer(strings.NewReplacer(".", "_"))
42+
3743
if len(c.Paths) == 0 {
3844
return v, nil
3945
}

internal/config/config_test.go

+31-1
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,8 @@ import (
44
"os"
55
"path/filepath"
66
"testing"
7+
8+
"github.com/stretchr/testify/require"
79
)
810

911
type testData struct {
@@ -41,7 +43,7 @@ func writeConfig(path, data string) error {
4143
return os.WriteFile(
4244
filepath.Join(path, "kuberlr.conf"),
4345
[]byte(data),
44-
0600)
46+
0o600)
4547
}
4648

4749
func TestOnlySystemConfigExists(t *testing.T) {
@@ -106,6 +108,34 @@ func TestHomeConfigOverridesSystemOne(t *testing.T) {
106108
}
107109
}
108110

111+
func TestEnvironmentVariables(t *testing.T) {
112+
td, err := setup()
113+
if err != nil {
114+
t.Error(err)
115+
}
116+
require.NoError(t, err)
117+
defer teardown(td)
118+
119+
err = writeConfig(td.FakeHome, "AllowDownload = false")
120+
if err != nil {
121+
t.Error(err)
122+
}
123+
124+
t.Setenv("KUBERLR_ALLOWDOWNLOAD", "true")
125+
126+
c := Cfg{
127+
Paths: []string{},
128+
}
129+
130+
v, err := c.Load()
131+
if err != nil {
132+
t.Errorf("Unexpected error loading config: %v", err)
133+
}
134+
if v.GetBool("AllowDownload") != true {
135+
t.Error("env var wasn't taken into account")
136+
}
137+
}
138+
109139
func TestMergeConfigs(t *testing.T) {
110140
td, err := setup()
111141
if err != nil {

0 commit comments

Comments
 (0)