Skip to content

Commit

Permalink
Escape environment variables during config toml parsing (#3637)
Browse files Browse the repository at this point in the history
(cherry picked from commit b0c2bb8)
  • Loading branch information
danielnelson committed Jan 4, 2018
1 parent 865917f commit fe6239c
Showing 1 changed file with 13 additions and 2 deletions.
15 changes: 13 additions & 2 deletions internal/config/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,11 @@ var (

// envVarRe is a regex to find environment variables in the config file
envVarRe = regexp.MustCompile(`\$\w+`)

envVarEscaper = strings.NewReplacer(
`"`, `\"`,
`\`, `\\`,
)
)

// Config specifies the URL/user/password for the database that telegraf
Expand Down Expand Up @@ -689,6 +694,11 @@ func trimBOM(f []byte) []byte {
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
// returns the AST produced from the TOML parser. When loading the file, it
// will find environment variables and replace them.
Expand All @@ -702,8 +712,9 @@ func parseFile(fpath string) (*ast.Table, error) {

env_vars := envVarRe.FindAll(contents, -1)
for _, env_var := range env_vars {
env_val := os.Getenv(strings.TrimPrefix(string(env_var), "$"))
if env_val != "" {
env_val, ok := os.LookupEnv(strings.TrimPrefix(string(env_var), "$"))
if ok {
env_val = escapeEnv(env_val)
contents = bytes.Replace(contents, env_var, []byte(env_val), 1)
}
}
Expand Down

0 comments on commit fe6239c

Please sign in to comment.