From b76ba32803df11b3fea475e143e75b15f473e966 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?V=C3=ADctor=20Cuadrado=20Juan?= Date: Wed, 5 Mar 2025 12:17:41 +0100 Subject: [PATCH] feat: Support environment variables for config settings MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 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 --- README.md | 4 ++++ internal/config/config.go | 6 ++++++ internal/config/config_test.go | 29 ++++++++++++++++++++++++++++- 3 files changed, 38 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index b75ad81..15e7f47 100644 --- a/README.md +++ b/README.md @@ -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. diff --git a/internal/config/config.go b/internal/config/config.go index 85a62e8..d3fd089 100644 --- a/internal/config/config.go +++ b/internal/config/config.go @@ -2,6 +2,7 @@ package config import ( "os" + "strings" "github.com/spf13/viper" @@ -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 } diff --git a/internal/config/config_test.go b/internal/config/config_test.go index 0f8163e..837712b 100644 --- a/internal/config/config_test.go +++ b/internal/config/config_test.go @@ -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) { @@ -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 {