github.com/teknogeek/dnscontrol/v2@v2.10.1-0.20200227202244-ae299b55ba42/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  )
    16  
    17  // 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]+
    18  func LoadProviderConfigs(fname string) (map[string]map[string]string, error) {
    19  	var results = map[string]map[string]string{}
    20  	dat, err := utfutil.ReadFile(fname, utfutil.POSIX)
    21  	if err != nil {
    22  		// no creds file is ok. Bind requires nothing for example. Individual providers will error if things not found.
    23  		if os.IsNotExist(err) {
    24  			fmt.Printf("INFO: Config file %q does not exist. Skipping.\n", fname)
    25  			return results, nil
    26  		}
    27  		return nil, fmt.Errorf("While reading provider credentials file %v: %v", fname, err)
    28  	}
    29  	s := string(dat)
    30  	r := JsonConfigReader.New(strings.NewReader(s))
    31  	err = json.NewDecoder(r).Decode(&results)
    32  	if err != nil {
    33  		return nil, fmt.Errorf("While parsing provider credentials file %v: %v", fname, err)
    34  	}
    35  	if err = replaceEnvVars(results); err != nil {
    36  		return nil, err
    37  	}
    38  	return results, nil
    39  }
    40  
    41  func replaceEnvVars(m map[string]map[string]string) error {
    42  	for _, keys := range m {
    43  		for k, v := range keys {
    44  			if strings.HasPrefix(v, "$") {
    45  				env := v[1:]
    46  				newVal := os.Getenv(env)
    47  				keys[k] = newVal
    48  			}
    49  		}
    50  	}
    51  	return nil
    52  }