Escape environment variables during config toml parsing (#3637)

(cherry picked from commit b0c2bb870e)
This commit is contained in:
Daniel Nelson 2018-01-04 15:28:00 -08:00 committed by Daniel Nelson
parent 865917f523
commit fe6239cf9f
No known key found for this signature in database
GPG Key ID: CAAD59C9444F6155
1 changed files with 13 additions and 2 deletions

View File

@ -40,6 +40,11 @@ var (
// envVarRe is a regex to find environment variables in the config file // envVarRe is a regex to find environment variables in the config file
envVarRe = regexp.MustCompile(`\$\w+`) envVarRe = regexp.MustCompile(`\$\w+`)
envVarEscaper = strings.NewReplacer(
`"`, `\"`,
`\`, `\\`,
)
) )
// Config specifies the URL/user/password for the database that telegraf // Config specifies the URL/user/password for the database that telegraf
@ -689,6 +694,11 @@ func trimBOM(f []byte) []byte {
return bytes.TrimPrefix(f, []byte("\xef\xbb\xbf")) return bytes.TrimPrefix(f, []byte("\xef\xbb\xbf"))
} }
// escapeEnv escapes a value for inserting into a TOML string.
func escapeEnv(value string) string {
return envVarEscaper.Replace(value)
}
// parseFile loads a TOML configuration from a provided path and // parseFile loads a TOML configuration from a provided path and
// returns the AST produced from the TOML parser. When loading the file, it // returns the AST produced from the TOML parser. When loading the file, it
// will find environment variables and replace them. // will find environment variables and replace them.
@ -702,8 +712,9 @@ func parseFile(fpath string) (*ast.Table, error) {
env_vars := envVarRe.FindAll(contents, -1) env_vars := envVarRe.FindAll(contents, -1)
for _, env_var := range env_vars { for _, env_var := range env_vars {
env_val := os.Getenv(strings.TrimPrefix(string(env_var), "$")) env_val, ok := os.LookupEnv(strings.TrimPrefix(string(env_var), "$"))
if env_val != "" { if ok {
env_val = escapeEnv(env_val)
contents = bytes.Replace(contents, env_var, []byte(env_val), 1) contents = bytes.Replace(contents, env_var, []byte(env_val), 1)
} }
} }