如何使用AWS SDK for Rust获取我假定角色的凭据?

wbrvyc0a  于 11个月前  发布在  其他
关注(0)|答案(1)|浏览(103)

我正在使用AWS SDK for Rust来承担在新帐户下发出请求的角色。
docs中的Python示例所示,我正在查找aws_access_key_idaws_secret_access_keyaws_session_token等凭据,
然而,Rust示例看起来不同,似乎没有显示底层凭据。
如何使用AWS SDK for Rust获取我假定角色的凭据?

wkftcu5l

wkftcu5l1#

Rust的例子并不是最好的(因为它在预览版中是公认的),它也有一个名为role_name的参数,而实际上它应该是role_arn
也就是说,要获得访问密钥ID,秘密访问密钥和会话令牌-就像Python示例一样-**使用AssumeRoleProvider**的ProvideCredentials方法。

let provider = aws_config::sts::AssumeRoleProvider::builder(role_arn)
    .session_name(session_name.unwrap())
    .configure(config)
    .build()
    .await;

let credentials = provider.provide_credentials().await.unwrap();

println!("AWS Access Key ID: {}", credentials.access_key_id());
println!("AWS Secret Access Key: {}", credentials.secret_access_key());
println!("AWS Session Token: {}", credentials.session_token().unwrap_or_default());

字符串
下面是一个完整但最小的工作Rust CLI应用程序来演示上述内容:

// cargo.toml

[package]
name = "aws-sdk-for-rust-assume-role-demo"
version = "0.1.0"
edition = "2021"

[dependencies]
aws-config = "0.57.1"
aws-credential-types="0.57.1"
aws-types="0.57.1"
tokio = { version = "1", features = ["full"] }

// main.rs

use aws_config::SdkConfig;
use aws_credential_types::provider::ProvideCredentials;

#[tokio::main]
async fn main() {
    let config = aws_config::load_from_env().await;
    let role_arn = "arn:aws:iam::xxx:role/xxx".to_string();
    let session_name = Option::from("xxx".to_string());

    assume_role(&config, role_arn, session_name).await;
}

async fn assume_role(config: &SdkConfig, role_arn: String, session_name: Option<String>) {
    let provider = aws_config::sts::AssumeRoleProvider::builder(role_arn)
        .session_name(session_name.unwrap())
        .configure(config)
        .build()
        .await;

    let credentials = provider.provide_credentials().await.unwrap();
    println!("AWS Access Key ID: {}", credentials.access_key_id());
    println!("AWS Secret Access Key: {}", credentials.secret_access_key());
    println!("AWS Session Token: {}", credentials.session_token().unwrap_or_default());
}

相关问题