Skip to content

Commit

Permalink
fix (api): env variables load (#1117)
Browse files Browse the repository at this point in the history
Signed-off-by: Yvonnick Esnault <yvonnick.esnault@corp.ovh.com>
  • Loading branch information
yesnault authored and sguiheux committed Sep 20, 2017
1 parent fce15cf commit 04c48a6
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 12 deletions.
20 changes: 9 additions & 11 deletions engine/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import (
"os"
"strings"

defaults "github.com/mcuadros/go-defaults"
"github.com/spf13/viper"

"github.com/ovh/cds/engine/api/secret"
Expand All @@ -14,6 +15,10 @@ import (

// config reads in config file and ENV variables if set.
func config() {
for k := range AsEnvVariables(conf, "") {
viper.BindEnv(strings.ToLower(strings.Replace(k, "_", ".", -1)), "CDS_"+k)
}

if cfgFile != "" {
//If the config file doesn't exists, let's exit
if _, err := os.Stat(cfgFile); os.IsNotExist(err) {
Expand All @@ -26,9 +31,6 @@ func config() {
sdk.Exit(err.Error())
}

if err := viper.Unmarshal(conf); err != nil {
sdk.Exit(err.Error())
}
} else if remoteCfg != "" {
fmt.Println("Reading configuration from consul @", remoteCfg)
viper.AddRemoteProvider("consul", remoteCfg, remoteCfgKey)
Expand Down Expand Up @@ -56,14 +58,10 @@ func config() {
if err := viper.ReadConfig(cfgBuffer); err != nil {
sdk.Exit("Unable to read config: %v", err.Error())
}

// Unmarshal in the conf
if err := viper.Unmarshal(conf); err != nil {
sdk.Exit("Unable to parse config: %v", err.Error())
}
}

viper.AutomaticEnv() // read in environment variables that match
viper.SetEnvPrefix("cds")
viper.SetEnvKeyReplacer(strings.NewReplacer(".", "_", "-", "_")) // Replace "." and "-" by "_" for env variable lookup
if err := viper.Unmarshal(conf); err != nil {
sdk.Exit("Unable to parse config: %v", err.Error())
}
defaults.SetDefaults(conf)
}
6 changes: 5 additions & 1 deletion engine/types.go
Original file line number Diff line number Diff line change
Expand Up @@ -46,13 +46,17 @@ type Service interface {
func AsEnvVariables(o interface{}, prefix string) map[string]string {
r := map[string]string{}
prefix = strings.ToUpper(prefix)
delim := "_"
if prefix == "" {
delim = ""
}
fields := structs.Fields(o)
for _, f := range fields {
if commented, _ := strconv.ParseBool(f.Tag("commented")); commented {
continue
}
if structs.IsStruct(f.Value()) {
rf := AsEnvVariables(f.Value(), prefix+"_"+f.Name())
rf := AsEnvVariables(f.Value(), prefix+delim+f.Name())
for k, v := range rf {
r[k] = v
}
Expand Down

0 comments on commit 04c48a6

Please sign in to comment.