diff --git a/README.md b/README.md index 04a72be..6c17657 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 + +Important 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..7f37abc 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,9 @@ func Execute() { } func NewRootCmd(c *config.Config) *cobra.Command { + viper.SetEnvPrefix(strings.ToUpper(config.ConfigDir)) + viper.SetEnvKeyReplacer(strings.NewReplacer("-", "_")) + rootCmd := &cobra.Command{ Use: config.BinaryName, Aliases: []string{"m"}, @@ -72,6 +76,13 @@ func NewRootCmd(c *config.Config) *cobra.Command { genericcli.Must(viper.BindPFlags(rootCmd.PersistentFlags())) + viper.MustBindEnv("config") + viper.MustBindEnv("force-color") + viper.MustBindEnv("debug") + viper.MustBindEnv("timeout") + viper.MustBindEnv("api-url") + viper.MustBindEnv("api-token") + markdownCmd := &cobra.Command{ Use: "markdown", Short: "create markdown documentation",