From 557f1a39749344ce0bccee02a31ae3e49ff706c9 Mon Sep 17 00:00:00 2001 From: Markus Wennrich Date: Tue, 29 Sep 2026 09:07:18 +0200 Subject: [PATCH] enable environment based configuration --- README.md | 6 ++++++ cmd/config/config.go | 2 +- cmd/root.go | 5 +++++ 3 files changed, 12 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index 04a72be..2be37a5 100644 --- a/README.md +++ b/README.md @@ -110,3 +110,9 @@ $ metalctlv2 ctx add --activate --default-project ``` The configuration file is by default written to `~/.metal-stack/config.yaml`. + +## Environment Variables + +All flags can also be provided as environment variables prefixed with `METAL_STACK_`. The flag name is uppercased and dashes are replaced by underscores, e.g. `--api-url` becomes `METAL_STACK_API_URL`. + +An explicitly provided flag takes precedence over an environment variable, which in turn takes precedence over the context in `~/.metal-stack/config.yaml`. diff --git a/cmd/config/config.go b/cmd/config/config.go index fdc692c..a83c3b5 100644 --- a/cmd/config/config.go +++ b/cmd/config/config.go @@ -21,7 +21,7 @@ const ( // BinaryName is the name of the cli in all help texts BinaryName = "metalctlv2" // ConfigDir is the directory in either the homedir or in /etc where the cli searches for a file config.yaml - // also used as prefix for environment based configuration, e.g. METAL_STACK_CLOUD_ will be the variable prefix. + // also used as prefix for environment based configuration, e.g. METAL_STACK_ will be the variable prefix. ConfigDir = "metal-stack" ) diff --git a/cmd/root.go b/cmd/root.go index 821a391..e9adb01 100644 --- a/cmd/root.go +++ b/cmd/root.go @@ -3,6 +3,7 @@ package cmd import ( "log/slog" "os" + "strings" client "github.com/metal-stack/api/go/client" "github.com/metal-stack/metal-lib/pkg/genericcli" @@ -42,6 +43,10 @@ func Execute() { } func NewRootCmd(c *config.Config) *cobra.Command { + viper.SetEnvPrefix(strings.ToUpper(config.ConfigDir)) + viper.SetEnvKeyReplacer(strings.NewReplacer("-", "_")) + viper.AutomaticEnv() + rootCmd := &cobra.Command{ Use: config.BinaryName, Aliases: []string{"m"},