From 2d2079d190ff459ccbc2ab9ba84792eccbc2e073 Mon Sep 17 00:00:00 2001 From: Kevin Petremann Date: Sat, 8 Jul 2023 22:28:11 +0200 Subject: [PATCH] feat: configuration via environment variables All settings available in the configuration file can be set as environment variables, but: - all variables must be prefixed by `SALT_` - uppercase only - `-` in the configuration file becomes a `_` - `__` is the level separator The precedence order is the one coming from viper: - flags - environment variables - configuration file --- README.md | 48 +++++++++++++++++++++++++++++++++---- cmd/salt-exporter/config.go | 4 ++++ 2 files changed, 47 insertions(+), 5 deletions(-) diff --git a/README.md b/README.md index 279c5e2..54513f1 100644 --- a/README.md +++ b/README.md @@ -53,10 +53,18 @@ metrics: ## Usage +### Run + Simply run: ```./salt-exporter``` -The exporter can be configured using flags: +The exporter can be configured in different ways, with the following precedence order: +* flags +* environment variables +* configuration file (config.yml) + +### Flags + ``` ./salt-exporter -help -health-functions-filter string @@ -83,9 +91,41 @@ The exporter can be configured using flags: TLS private key ``` -It can also be configured via a `config.yml` file, which provides more customization. +### Environment variables + +All settings available in the configuration file can be set as environment variables, but: + +* all variables must be prefixed by `SALT_` +* uppercase only +* `-` in the configuration file becomes a `_` +* `__` is the level separator + +For example, the equivalent of this config file: + +```yaml +log-level: "info" +tls: + enabled: true +metrics: + global: + filters: + ignore-test: true +``` + +is: + +``` +SALT_LOG_LEVEL="info" +SALT_TLS__ENABLED=true +SALT_METRICS__GLOBAL__FILTERS__IGNORE_TEST=true +``` + +### Configuration file + +The exporter is looking for `config.yml`. + +See below a full example of a configuration file: -The default settings are: ```yaml listen-address: "" listen-port: 2112 @@ -129,8 +169,6 @@ metrics: - "highstate" ``` -**Note: Except for -health-minions, all flags have the priority over the configuration file.** - ## Features Supported tags: diff --git a/cmd/salt-exporter/config.go b/cmd/salt-exporter/config.go index 4929fdf..d732b62 100644 --- a/cmd/salt-exporter/config.go +++ b/cmd/salt-exporter/config.go @@ -109,6 +109,10 @@ func getConfig(configFileName string, healthMinions bool) (Config, error) { viper.SetConfigType(strings.TrimPrefix(ext, ".")) viper.AddConfigPath(".") + viper.SetEnvKeyReplacer(strings.NewReplacer("-", "_", ".", "__")) + viper.SetEnvPrefix("SALT") + viper.AutomaticEnv() + err := viper.ReadInConfig() if err != nil { if _, ok := err.(viper.ConfigFileNotFoundError); !ok {