answering the question about how to re-assume a role(rather then 'dropping it') here:
while you can't directly 'revoke' session token using the aws cli or, 're-assume' a role when the role is specified as aws cli profile, you can achieve similar results by assuming the role directly by calling the sts:AssumeRole API using the aws CLI, and then setting AWS_ACCESS_KEY_ID
,AWS_SECRET_ACCESS_KEY
,AWS_SESSION_TOKEN
,AWS_DEFAULT_REGION
as environment variable.
you can use this script to assume a role, and each invocation would override the session token with new one
#!/bin/bash
# Run aws sts assume-role and capture the output
assume_role_output=$(aws sts assume-role "$@" | cat)
# Extract temporary credentials from the output
export AWS_ACCESS_KEY_ID=$(echo $assume_role_output | jq -r '.Credentials.AccessKeyId')
export AWS_SECRET_ACCESS_KEY=$(echo $assume_role_output | jq -r '.Credentials.SecretAccessKey')
export AWS_SESSION_TOKEN=$(echo $assume_role_output | jq -r '.Credentials.SessionToken')
# Extract AWS_DEFAULT_REGION from the --region parameter
AWS_DEFAULT_REGION=$(echo "$@" | awk -F'--region ' '{print $2}' | awk '{print $1}')
export AWS_DEFAULT_REGION
# Display the exported variables
echo "AWS_ACCESS_KEY_ID: $AWS_ACCESS_KEY_ID"
echo "AWS_SECRET_ACCESS_KEY: $AWS_SECRET_ACCESS_KEY"
echo "AWS_SESSION_TOKEN: $AWS_SESSION_TOKEN"
echo "AWS_DEFAULT_REGION: $AWS_DEFAULT_REGION"
note that the previous session token would remain valid until expires(usually 1 hour).
usage:
~/development/aws/training ······································································································································· 19:55:14 ─╮
❯ source assume-role --profile mine --role-arn arn:aws:iam::************:role/mine-admin-role --role-session-name mine-role-session --region us-east-1 ─╯
AWS_ACCESS_KEY_ID: ************
AWS_SECRET_ACCESS_KEY: ************
AWS_SESSION_TOKEN: ************
AWS_DEFAULT_REGION: us-east-1
~/development/aws/training ······································································································································· 20:07:53 ─╮
❯ aws sts get-caller-identity | cat ─╯
{
"UserId": "************:mine-role-session",
"Account": "************",
"Arn": "arn:aws:sts::************:assumed-role/mine-admin-role/mine-role-session"
note that are executing it with source
so that the env variables would apply in your shell session.
works like a charm.