Skip to content

Commit 04c48a6

Browse files
yesnaultsguiheux
authored andcommitted
fix (api): env variables load (#1117)
Signed-off-by: Yvonnick Esnault <[email protected]>
1 parent fce15cf commit 04c48a6

File tree

2 files changed

+14
-12
lines changed

2 files changed

+14
-12
lines changed

engine/config.go

+9-11
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@ import (
66
"os"
77
"strings"
88

9+
defaults "github.com/mcuadros/go-defaults"
910
"github.com/spf13/viper"
1011

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

1516
// config reads in config file and ENV variables if set.
1617
func config() {
18+
for k := range AsEnvVariables(conf, "") {
19+
viper.BindEnv(strings.ToLower(strings.Replace(k, "_", ".", -1)), "CDS_"+k)
20+
}
21+
1722
if cfgFile != "" {
1823
//If the config file doesn't exists, let's exit
1924
if _, err := os.Stat(cfgFile); os.IsNotExist(err) {
@@ -26,9 +31,6 @@ func config() {
2631
sdk.Exit(err.Error())
2732
}
2833

29-
if err := viper.Unmarshal(conf); err != nil {
30-
sdk.Exit(err.Error())
31-
}
3234
} else if remoteCfg != "" {
3335
fmt.Println("Reading configuration from consul @", remoteCfg)
3436
viper.AddRemoteProvider("consul", remoteCfg, remoteCfgKey)
@@ -56,14 +58,10 @@ func config() {
5658
if err := viper.ReadConfig(cfgBuffer); err != nil {
5759
sdk.Exit("Unable to read config: %v", err.Error())
5860
}
59-
60-
// Unmarshal in the conf
61-
if err := viper.Unmarshal(conf); err != nil {
62-
sdk.Exit("Unable to parse config: %v", err.Error())
63-
}
6461
}
6562

66-
viper.AutomaticEnv() // read in environment variables that match
67-
viper.SetEnvPrefix("cds")
68-
viper.SetEnvKeyReplacer(strings.NewReplacer(".", "_", "-", "_")) // Replace "." and "-" by "_" for env variable lookup
63+
if err := viper.Unmarshal(conf); err != nil {
64+
sdk.Exit("Unable to parse config: %v", err.Error())
65+
}
66+
defaults.SetDefaults(conf)
6967
}

engine/types.go

+5-1
Original file line numberDiff line numberDiff line change
@@ -46,13 +46,17 @@ type Service interface {
4646
func AsEnvVariables(o interface{}, prefix string) map[string]string {
4747
r := map[string]string{}
4848
prefix = strings.ToUpper(prefix)
49+
delim := "_"
50+
if prefix == "" {
51+
delim = ""
52+
}
4953
fields := structs.Fields(o)
5054
for _, f := range fields {
5155
if commented, _ := strconv.ParseBool(f.Tag("commented")); commented {
5256
continue
5357
}
5458
if structs.IsStruct(f.Value()) {
55-
rf := AsEnvVariables(f.Value(), prefix+"_"+f.Name())
59+
rf := AsEnvVariables(f.Value(), prefix+delim+f.Name())
5660
for k, v := range rf {
5761
r[k] = v
5862
}

0 commit comments

Comments
 (0)