fix(backend): correctly load configuration using CONFIG_FILE env variable

Fixes #1466
This commit is contained in:
Łukasz Mierzwa
2020-02-26 10:27:49 +00:00
parent afd7314a55
commit bd2017314f
5 changed files with 75 additions and 3 deletions

View File

@@ -0,0 +1,28 @@
# Loads config file from flags when CONFIG_FILE env is also set
env CONFIG_FILE=env.yaml
karma.bin-should-work --check-config --config.file=flag.yaml
! stdout .
stderr 'msg="Reading configuration file flag.yaml"'
stderr 'msg="Configuration is valid"'
stderr 'msg="\[flag\] Configured Alertmanager source at http://localhost:8080 \(proxied: false\, readonly: false\)"'
! stderr 'level=error'
! stderr 'msg="Reading configuration file karma.yaml"'
! stderr 'msg="Reading configuration file env.yaml"'
-- flag.yaml --
alertmanager:
servers:
- name: flag
uri: "http://localhost:8080"
-- env.yaml --
alertmanager:
servers:
- name: env
uri: "http://localhost:8080"
-- karma.yaml --
alertmanager:
servers:
- name: karma
uri: "http://localhost:8080"

View File

@@ -0,0 +1,15 @@
# Loads config file from CONFIG_FILE env
env CONFIG_FILE=foo.yaml
karma.bin-should-work --check-config
! stdout .
stderr 'msg="Reading configuration file foo.yaml"'
stderr 'msg="Configuration is valid"'
stderr 'msg="\[cwd\] Configured Alertmanager source at http://localhost:8080 \(proxied: true\, readonly: false\)"'
! stderr 'level=error'
-- foo.yaml --
alertmanager:
servers:
- name: cwd
uri: "http://localhost:8080"
proxy: true

View File

@@ -0,0 +1,15 @@
# Loads config file from --config.file flag
env CONFIG_FILE=foo.yaml
karma.bin-should-work --check-config --config.file foo.yaml
! stdout .
stderr 'msg="Reading configuration file foo.yaml"'
stderr 'msg="Configuration is valid"'
stderr 'msg="\[cwd\] Configured Alertmanager source at http://localhost:8080 \(proxied: true\, readonly: false\)"'
! stderr 'level=error'
-- foo.yaml --
alertmanager:
servers:
- name: cwd
uri: "http://localhost:8080"
proxy: true

View File

@@ -0,0 +1,6 @@
# Fails on invalid flag usage
env CONFIG_FILE=foo.yaml
karma.bin-should-fail --check-config --invalid.flag
! stdout .
! stderr 'msg="Configuration is valid"'
stderr 'level=error msg="unknown flag: --invalid.flag"'

View File

@@ -121,9 +121,17 @@ func SetupFlags(f *pflag.FlagSet) {
}
func readConfigFile(k *koanf.Koanf, flags *pflag.FlagSet) string {
configFile, _ := flags.GetString("config.file")
// if config.file is not passed via flags then see if there's karma.yaml in
// current working directory
var configFile string
// 1. Load file from flags is set
configFile, _ = flags.GetString("config.file")
// 2. Fallback to CONFIG_FILE env if there's no flag value
if configFile == "" {
if v, found := os.LookupEnv("CONFIG_FILE"); found {
configFile = v
}
}
// 3 see if there's karma.yaml in current working directory
if configFile == "" {
if _, err := os.Stat("karma.yaml"); !os.IsNotExist(err) {
configFile = "karma.yaml"