github.com/StackExchange/DNSControl@v0.2.8/providers/config/providerConfig.go (about) 1 // Package config provides functions for reading and parsing the provider credentials json file. 2 // It cleans nonstandard json features (comments and trailing commas), as well as replaces environment variable placeholders with 3 // their environment variable equivalents. To reference an environment variable in your json file, simply use values in this format: 4 // "key"="$ENV_VAR_NAME" 5 package config 6 7 import ( 8 "encoding/json" 9 "fmt" 10 "os" 11 "strings" 12 13 "github.com/DisposaBoy/JsonConfigReader" 14 "github.com/TomOnTime/utfutil" 15 "github.com/pkg/errors" 16 ) 17 18 // LoadProviderConfigs will open the specified file name, and parse its contents. It will replace environment variables it finds if any value matches $[A-Za-z_-0-9]+ 19 func LoadProviderConfigs(fname string) (map[string]map[string]string, error) { 20 var results = map[string]map[string]string{} 21 dat, err := utfutil.ReadFile(fname, utfutil.POSIX) 22 if err != nil { 23 // no creds file is ok. Bind requires nothing for example. Individual providers will error if things not found. 24 if os.IsNotExist(err) { 25 fmt.Printf("INFO: Config file %q does not exist. Skipping.\n", fname) 26 return results, nil 27 } 28 return nil, errors.Errorf("While reading provider credentials file %v: %v", fname, err) 29 } 30 s := string(dat) 31 r := JsonConfigReader.New(strings.NewReader(s)) 32 err = json.NewDecoder(r).Decode(&results) 33 if err != nil { 34 return nil, errors.Errorf("While parsing provider credentials file %v: %v", fname, err) 35 } 36 if err = replaceEnvVars(results); err != nil { 37 return nil, err 38 } 39 return results, nil 40 } 41 42 func replaceEnvVars(m map[string]map[string]string) error { 43 for _, keys := range m { 44 for k, v := range keys { 45 if strings.HasPrefix(v, "$") { 46 env := v[1:] 47 newVal := os.Getenv(env) 48 keys[k] = newVal 49 } 50 } 51 } 52 return nil 53 }