Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -174,7 +174,7 @@ scrape_configs:
```

You could pass `username`, `password` & `priv_password` via environment variables of your choice in below format.
If the variables exist in the environment, they are resolved on the fly otherwise the string in the config file is passed as-is.
If the variables exist in the environment, they are resolved on the fly, otherwise `snmp_exporter` will error while loading the config.

This requires the `--config.expand-environment-variables` flag be set.

Expand Down
11 changes: 8 additions & 3 deletions config/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -361,11 +361,16 @@ func (re *Regexp) UnmarshalYAML(unmarshal func(interface{}) error) error {
}

func substituteEnvVariables(value string) (string, error) {
var missingEnv = ""
result := os.Expand(value, func(s string) string {
return os.Getenv(s)
v := os.Getenv(s)
if v == "" && missingEnv == "" {
missingEnv = s
}
return v
})
if result == "" {
return "", errors.New(value + " environment variable not found")
if missingEnv != "" {
return "", errors.New(missingEnv + " environment variable not found")
}
return result, nil
}
5 changes: 4 additions & 1 deletion config_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -73,7 +73,7 @@ func TestLoadMultipleConfigs(t *testing.T) {

// When all environment variables are present
func TestEnvSecrets(t *testing.T) {
t.Setenv("ENV_USERNAME", "snmp_username")
t.Setenv("ENV_USERNAME", "username") // snmp_ prefix is set in config file
t.Setenv("ENV_PASSWORD", "snmp_password")
t.Setenv("ENV_PRIV_PASSWORD", "snmp_priv_password")

Expand Down Expand Up @@ -110,6 +110,9 @@ func TestEnvSecretsMissing(t *testing.T) {

sc := &SafeConfig{}
err := sc.ReloadConfig(nopLogger, []string{"testdata/snmp-auth-envvars.yml"}, true)
if err == nil {
t.Fatal("no error despite missing env var")
}
if err != nil {
// we check the error message pattern to determine the error
if strings.Contains(err.Error(), "environment variable not found") {
Expand Down
2 changes: 1 addition & 1 deletion testdata/snmp-auth-envvars.yml
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ auths:
with_secret:
community: mysecret
security_level: SomethingReadOnly
username: ${ENV_USERNAME}
username: snmp_${ENV_USERNAME}
password: ${ENV_PASSWORD}
auth_protocol: SHA256
priv_protocol: AES
Expand Down