github.com/philhug/dnscontrol@v0.2.4-0.20180625181521-921fa9849001/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  	"os"
    10  	"strings"
    11  
    12  	"github.com/DisposaBoy/JsonConfigReader"
    13  	"github.com/TomOnTime/utfutil"
    14  	"github.com/pkg/errors"
    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  			return results, nil
    25  		}
    26  		return nil, errors.Errorf("While reading provider credentials file %v: %v", fname, err)
    27  	}
    28  	s := string(dat)
    29  	r := JsonConfigReader.New(strings.NewReader(s))
    30  	err = json.NewDecoder(r).Decode(&results)
    31  	if err != nil {
    32  		return nil, errors.Errorf("While parsing provider credentials file %v: %v", fname, err)
    33  	}
    34  	if err = replaceEnvVars(results); err != nil {
    35  		return nil, err
    36  	}
    37  	return results, nil
    38  }
    39  
    40  func replaceEnvVars(m map[string]map[string]string) error {
    41  	for _, keys := range m {
    42  		for k, v := range keys {
    43  			if strings.HasPrefix(v, "$") {
    44  				env := v[1:]
    45  				newVal := os.Getenv(env)
    46  				keys[k] = newVal
    47  			}
    48  		}
    49  	}
    50  	return nil
    51  }