Crates.io | config-secret |
lib.rs | config-secret |
version | 0.1.0 |
source | src |
created_at | 2023-06-21 17:37:50.422617 |
updated_at | 2023-06-21 17:37:50.422617 |
description | A source for the config crate that follows the Docker/Kubernetes secret configuration convention |
homepage | https://github.com/touchifyapp/config-secret-rs |
repository | https://github.com/touchifyapp/config-secret-rs |
max_upload_size | |
id | 896404 |
size | 24,219 |
config-secret
is an additional source for the config crate that follows the Docker/Kubernetes convention.
It allows to inject some parts of your configuration by using a file specified as environment variable. See examples.
[dependencies]
config = "0.13"
config-secret = "0.1.0"
use config::Config;
use config_secret::EnvironmentSecretFile;
let source = EnvironmentSecretFile::with_prefix("APP").separator("_");
let config = Config::builder().add_source(source).build().unwrap();
let settings = config.try_deserialize::<Settings>().unwrap();
// settings...
Let's introduce our types and our config
initializer:
use config::{Config, ConfigError};
use config_secret::EnvironmentSecretFile;
use serde::Deserialize;
#[derive(Deserialize, Clone, Debug)]
pub struct Settings {
pub server: ServerSettings,
pub redis: RedisSettings,
}
#[derive(Deserialize, Clone, Debug)]
pub struct ServerSettings {
pub host: String,
pub port: u16,
}
#[derive(Deserialize, Clone, Debug)]
pub struct RedisSettings {
pub nodes: Vec<String>,
pub username: Option<String>,
pub password: Option<String>,
}
pub fn get_settings() -> Result<Settings, ConfigError> {
let config = Config::builder()
.add_source(
config::Environment::with_prefix("APP")
.separator("_")
.list_separator(",")
.with_list_parse_key("redis.nodes")
.try_parsing(true),
)
.add_source(
EnvironmentSecretFile::with_prefix("APP")
.separator("_")
)
.build()?;
config.try_deserialize::<Settings>()
}
We can add an environment variable to set a secret that configure the whole configuration:
APP_FILE=/run/secrets/my_secret.json
{
"server": {
"host": "0.0.0.0",
"port": 5000
},
"redis": {
"nodes": [
"redis://10.0.0.1:6379",
"redis://10.0.0.2:6379",
"redis://10.0.0.3:6379"
]
}
}
let settings = get_settings().unwrap();
assert!(settings.server.host == "0.0.0.0");
We can add environments variables that set only a sub section of your configuration:
APP_SERVER_HOST=127.0.0.1
APP_SERVER_PORT=5000
APP_REDIS_FILE=/run/secrets/redis.yaml
nodes:
- redis://10.0.0.1:6379
- redis://10.0.0.2:6379
- redis://10.0.0.3:6379
username: redis
password: superpassword
let settings = get_settings().unwrap();
assert!(settings.server.host == "127.0.0.1");
assert!(settings.redis.username == "redis");