Crate figment_file_env_provider

Source
Expand description

Figment figment::Provider for optionally file-based env config values.

use serde::Deserialize;
use figment::{Figment, providers::Env};
use figment_file_env_provider::FileEnv;

#[derive(Deserialize)]
struct Config {
  frobnicate: String,
  foo: u64,
}

let config: Config = Figment::new()
    .merge(FileEnv::from_env(Env::prefixed("APP_")))
    .extract()?;

§Overview

This crate contains the FileEnv provider for figment, to allow loading configuration values from either environment variables or files. This is especially useful for secret management in combination with containers.

For instance, to pass an API key to the configuration, you could use either the environment variable API_KEY=abc123deadbeef, or you could write that API key to a file /secrets/api_key and pass the env variable API_KEY_FILE=/secrets/api_key.

Note that if both are specified, the non-_FILE one wins.

§Recommendations

§Namespacing and restricting the variables read

The provider will try to read any environment variable that ends with _FILE (or the custom suffix) and will error if the file cannot be read. As such, it is usually necessary to have a namespace for the environment variables in the form of a unique prefix, to avoid conficts or unexpected interactions: FileEnv::from_env(Env::prefixed("MY_APP_")) (see figment::providers::Env::prefixed).

Since it is built on top of figment::providers::Env, you can set it up so that only some variables accept the _FILE variant and the rest are read normally with FileEnv::only:

let file_keys = ["foo", "bar"];
let env = Env::prefixed("APP_");
// Call `.only` on the FileEnv, not the Env.
let config: Config = Figment::new()
    .merge(FileEnv::from_env(env.clone()).only(&file_keys))
    .merge(env.ignore(&file_keys))
    .extract()?;

§Changing the suffix

You can also specify the suffix to use. For instance, to use “_PATH” instead of “_FILE”:

let config: Config = Figment::new()
    .merge(FileEnv::from_env(Env::prefixed("APP_")).with_suffix("_PATH"))
    .extract()?;

Structs§

FileEnv
Provider that reads config values from the environment or from files pointed to by the environment.
FileEnvWithRestrictions
A FileEnv that cannot have its suffix changed anymore.