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

feat: Support environment variables for config settings #181

Merged
merged 1 commit into from
Mar 5, 2025
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
4 changes: 4 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -131,3 +131,7 @@ Timeout = 1
# Default "https://dl.k8s.io"
KubeMirrorUrl = "https://dl.k8s.io"
```

The behaviour can also be adjusted by using environment variables matching the
config file: `KUBERLR_ALLOWDOWNLOAD`, `KUBERLR_SYSTEMPATH`, `KUBERLR_TIMEOUT`,
`KUBERLR_KUBEMIRRORURL`, and so on.
6 changes: 6 additions & 0 deletions internal/config/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package config

import (
"os"
"strings"

"github.com/spf13/viper"

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

v.SetConfigType("toml")

// read environment variables, they take precedence
v.AutomaticEnv()
v.SetEnvPrefix("KUBERLR")
v.SetEnvKeyReplacer(strings.NewReplacer(".", "_"))

if len(c.Paths) == 0 {
return v, nil
}
Expand Down
29 changes: 28 additions & 1 deletion internal/config/config_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,7 @@ func writeConfig(path, data string) error {
return os.WriteFile(
filepath.Join(path, "kuberlr.conf"),
[]byte(data),
0600)
0o600)
}

func TestOnlySystemConfigExists(t *testing.T) {
Expand Down Expand Up @@ -106,6 +106,33 @@ func TestHomeConfigOverridesSystemOne(t *testing.T) {
}
}

func TestEnvironmentVariables(t *testing.T) {
td, err := setup()
if err != nil {
t.Error(err)
}
defer teardown(td)

err = writeConfig(td.FakeHome, "AllowDownload = false")
if err != nil {
t.Error(err)
}

t.Setenv("KUBERLR_ALLOWDOWNLOAD", "true")

c := Cfg{
Paths: []string{},
}

v, err := c.Load()
if err != nil {
t.Errorf("Unexpected error loading config: %v", err)
}
if v.GetBool("AllowDownload") != true {
t.Error("env var wasn't taken into account")
}
}

func TestMergeConfigs(t *testing.T) {
td, err := setup()
if err != nil {
Expand Down
Loading