Set AWS Secrets Manager values to environment variables in rust


How to use AWS Secrets Manager for storing confidential information such as API Keys.

Configuration of Cargo.toml

[dependencies]
aws-config = "..."
aws-sdk-secretsmanager = "..."

Secrets Manager secret values (example)

{"OPENAI_API_KEY":"sk-...."}

Source code for rust


use std::env;
use anyhow::Result;
use std::collections::HashMap;
use aws_types::region::Region;
use aws_sdk_secretsmanager as secretsmanager;

async fn load_secrets(secret_name: &str, region: &Option<String>) -> anyhow::Result<()> {    
    let config = load_aws_config(region).await;
    let client = secretsmanager::Client::new(&config);
    let resp = client
        .get_secret_value()
        .secret_id(secret_name)
        .send()
        .await?;

    let Some(secret_string) = resp.secret_string() else {
        return Ok(());
    };

    let js: HashMap<String, String> = serde_json::from_str(secret_string)?;

    for (k, v) in js.iter() {
        env::set_var(k, v);
    }
    Ok(())
}

async fn load_aws_config(region: &Option<String>) -> aws_config::SdkConfig {    
    if let Some(ref region) = region {
        aws_config::from_env()
            .region(Region::new(region.clone()))
            .load()
            .await
    } else {
        aws_config::from_env().load().await
    }
}

See also