Skip to content

Commit 18edcfb

Browse files
authored
Merge pull request #181 from viccuad/main
feat: Support environment variables for config settings
2 parents 280d9d9 + b76ba32 commit 18edcfb

File tree

3 files changed

+38
-1
lines changed

3 files changed

+38
-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

+28-1
Original file line numberDiff line numberDiff line change
@@ -41,7 +41,7 @@ func writeConfig(path, data string) error {
4141
return os.WriteFile(
4242
filepath.Join(path, "kuberlr.conf"),
4343
[]byte(data),
44-
0600)
44+
0o600)
4545
}
4646

4747
func TestOnlySystemConfigExists(t *testing.T) {
@@ -106,6 +106,33 @@ func TestHomeConfigOverridesSystemOne(t *testing.T) {
106106
}
107107
}
108108

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

0 commit comments

Comments
 (0)