Skip to content

Commit

Permalink
Allow env variable override, without associated flags
Browse files Browse the repository at this point in the history
Visit manually env to bind every possibly related environment variable
to be able to unmarshall those into a struct.
More context on spf13/viper#1429.
  • Loading branch information
didrocks committed Oct 5, 2023
1 parent cab0274 commit 87e6ce2
Showing 1 changed file with 17 additions and 0 deletions.
17 changes: 17 additions & 0 deletions cmd/authd/daemon/config.go
Expand Up @@ -6,6 +6,7 @@ import (
"fmt"
"os"
"path/filepath"
"strings"

"github.com/spf13/cobra"
"github.com/spf13/viper"
Expand Down Expand Up @@ -59,6 +60,22 @@ func initViperConfig(name string, cmd *cobra.Command, vip *viper.Viper) (err err
vip.SetEnvPrefix(name)
vip.AutomaticEnv()

// Visit manually env to bind every possibly related environment variable to be able to unmarshall
// those into a struct.
// More context on https://github.com/spf13/viper/pull/1429.
prefix := strings.ToUpper(name) + "_"
for _, e := range os.Environ() {
if !strings.HasPrefix(e, prefix) {
continue
}

s := strings.Split(e, "=")
k := strings.ReplaceAll(strings.TrimPrefix(s[0], prefix), "_", ".")
if err := vip.BindEnv(k, s[0]); err != nil {
return fmt.Errorf("could not bind environment variable: %w", err)
}
}

return nil
}

Expand Down

0 comments on commit 87e6ce2

Please sign in to comment.