amazon-web-servicesrustamazon-iamaws-stsaws-sdk-rust

How can I get the credentials for my assumed role using the AWS SDK for Rust?


I am using the AWS SDK for Rust to assume a role for making a request under a new account.

As shown in the Python example from the docs, I'm looking for credentials like aws_access_key_id, aws_secret_access_key and aws_session_token,

However, the Rust example looks different, and doesn't seem to surface the underlying credentials.

How can I get the credentials for my assumed role using the AWS SDK for Rust?


Solution

  • The Rust example isn't the best (as it's admittedly in preview) & also has an argument named role_name when it really should be role_arn...

    That said, to obtain the access key ID, secret access key & session token - just like the Python example - use the ProvideCredentials method of the AssumeRoleProvider.

    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());
    

    Here is a complete yet minimal working Rust CLI app to demonstrate the above:

    // 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());
    }