Skip to content

Instantly share code, notes, and snippets.

@pandulaDW
Created July 5, 2023 05:20
Show Gist options
  • Save pandulaDW/9945d68e67b5d3481a04f37d86baea94 to your computer and use it in GitHub Desktop.
Save pandulaDW/9945d68e67b5d3481a04f37d86baea94 to your computer and use it in GitHub Desktop.
A command line program to get temporary AWS credentials using an MFA device.
use aws_sdk_sts as sts;
use std::env;
#[tokio::main]
async fn main() {
let config = aws_config::load_from_env().await;
let client = sts::Client::new(&config);
let token_code = env::args().nth(1);
const MFA_SERIAL_NUMBER: &str = "<your aws mfa device arn>";
let response = client
.get_session_token()
.serial_number(MFA_SERIAL_NUMBER)
.set_token_code(token_code)
.send()
.await;
match response {
Ok(v) => {
let Some(credentials) = v.credentials() else {
eprintln!("Received empty credentials");
return;
};
print_env_variable("AWS_ACCESS_KEY_ID", credentials.access_key_id());
print_env_variable("AWS_SECRET_ACCESS_KEY", credentials.secret_access_key());
print_env_variable("AWS_SESSION_TOKEN", credentials.session_token());
}
Err(e) => {
eprintln!("Error requesting token: {}", e)
}
}
}
/// Should be evaluated by the eval command
fn print_env_variable(key: &str, value: Option<&str>) {
match value {
Some(v) => println!("export {key}={v}"),
None => panic!("value for key {key} is empty"),
}
}
@pandulaDW
Copy link
Author

To set the environment variables in a shell session in a Nix OS, run eval "$(cargo r mfa)"

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment