Arcones
Arcones

Reputation: 4662

AWS sts assume role in one command

To assume an AWS role in the CLI, I do the following command:

aws sts assume-role --role-arn arn:aws:iam::123456789123:role/myAwesomeRole --role-session-name test --region eu-central-1

This gives to me an output that follows the schema:

{
    "Credentials": {
        "AccessKeyId": "someAccessKeyId",
        "SecretAccessKey": "someSecretAccessKey",
        "SessionToken": "someSessionToken",
        "Expiration": "2020-08-04T06:52:13+00:00"
    },
    "AssumedRoleUser": {
        "AssumedRoleId": "idOfTheAssummedRole",
        "Arn": "theARNOfTheRoleIWantToAssume"
    }
}

And then I manually copy and paste the values of AccessKeyId, SecretAccessKey and SessionToken in a bunch of exports like this:

export AWS_ACCESS_KEY_ID="someAccessKeyId"                                                                                      
export AWS_SECRET_ACCESS_KEY="someSecretAccessKey"
export AWS_SESSION_TOKEN="someSessionToken"

To finally assume the role.

How can I do this in one go? I mean, without that manual intervention of copying and pasting the output of the aws sts ... command on the exports.

Upvotes: 133

Views: 119979

Answers (12)

Alexander Vyssokii
Alexander Vyssokii

Reputation: 1

Here is the variant which allows arbitrary arguments to be passed to the 'assume role' invocation.

A new sub-shell is opened so that the obtained credentials do not clutter the environment of the caller. When the credentials expire, it's easy to exit the sub-shell and obtain a new ones.

The invocation is:

sts-assume-in-a-shell --role-arn XXX --role-session-name YYY --external-id ZZZ

This is the shell function definition:

function sts-assume-in-a-shell() {
    eval $(printf "AWS_ACCESS_KEY_ID=%s AWS_SECRET_ACCESS_KEY=%s AWS_SESSION_TOKEN=%s" $( \
           aws sts assume-role $@ --query 'Credentials.[AccessKeyId,SecretAccessKey,SessionToken]' --output text \
    )) $SHELL
}

Upvotes: 0

LePirlouit
LePirlouit

Reputation: 501

I'm looking for the same, but for ... windows

Upvotes: 0

John Rotenstein
John Rotenstein

Reputation: 269350

You can store an IAM Role as a profile in the AWS CLI and it will automatically assume the role for you.

Here is an example from Using an IAM role in the AWS CLI - AWS Command Line Interface:

Example using configured profile as source

[profile marketingadmin]
role_arn = arn:aws:iam::123456789012:role/marketingadminrole
source_profile = user1

Example using ec2 instance profile as source

[profile marketingadmin]
role_arn = arn:aws:iam::123456789012:role/marketingadminrole
credential_source = Ec2InstanceMetadata

Example using ecs role attachaded profile as source

[profile marketingadmin]
role_arn = arn:aws:iam::123456789012:role/marketingadminrole
credential_source = EcsContainer

Example using enviroment variables (aws_profile or aws_secret_access, etc.. )

[profile marketingadmin]
role_arn = arn:aws:iam::123456789012:role/marketingadminrole
credential_source = Environment

This is saying:

  • If a user specifies --profile marketingadmin
  • Then use the credentials of source
  • To call AssumeRole on the specified role

This means you can simply call a command like this and it will assume the role and use the returned credentials automatically:

aws s3 ls --profile marketingadmin

Upvotes: 54

Kkameleon
Kkameleon

Reputation: 313

A robust script based on Nev Stoke's answer that just source the useful variables to your current shell session:

#!/bin/bash

# Check if the script is sourced or not
if [ "$0" = "$BASH_SOURCE" ]; then
    echo "This script needs to be sourced. Use the following command:"
    echo ". $BASH_SOURCE <account_id> <role_name> <role_session_name>"
    exit 1
fi

# Function to check prerequisites
check_prerequisites() {
    # Check if AWS CLI is installed
    if ! command -v aws &> /dev/null
    then
        echo "AWS CLI not installed. Please install it and try again."
        return 1
    fi

    # Check for correct number of arguments
    if [ "$#" -ne 3 ]; then
        echo "Usage: . $0 <account_id> <role_name> <role_session_name>"
        return 1
    fi
}

# Main function to assume role
assume_role() {
    # Assign arguments to variables
    account_id=$1
    role_name=$2
    role_session_name=$3

    # Construct role ARN
    role_arn="arn:aws:iam::${account_id}:role/${role_name}"

    # Assume the role and retrieve credentials
    read -r access_key secret_key session_token <<< $(aws sts assume-role \
                                                        --role-arn "$role_arn" \
                                                        --role-session-name "$role_session_name" \
                                                        --query "Credentials.[AccessKeyId,SecretAccessKey,SessionToken]" \
                                                        --output text)

    # Check if the credentials were successfully retrieved
    if [ -z "$access_key" ] || [ -z "$secret_key" ] || [ -z "$session_token" ]; then
        echo "Failed to assume role. Please check your inputs and AWS configuration."
        return 1
    fi

    # Export the credentials
    export AWS_ACCESS_KEY_ID=$access_key
    export AWS_SECRET_ACCESS_KEY=$secret_key
    export AWS_SESSION_TOKEN=$session_token

    echo "AWS credentials exported successfully."
}

# Run the checks
check_prerequisites "$@" || return 1

# If checks pass, assume the role
assume_role "$@"

Upvotes: 2

Ho Dang Hau
Ho Dang Hau

Reputation: 41

You can use aws config with external source following the guide: Sourcing credentials with an external process. Create a shell script, for example assume-role.sh:

#!/bin/sh
aws sts --profile $2 assume-role --role-arn arn:aws:iam::123456789012:role/$1 \
                                 --role-session-name test \
                                 --query "Credentials" \
                                | jq --arg version 1 '. + {Version: $version|tonumber}'   

At ~/.aws/config config profile with shell script:

[profile desktop]
region=ap-southeast-1
output=json
    
[profile external-test]
credential_process = "/path/assume-role.sh" test desktop
    
[profile external-test2]
credential_process = "/path/assume-role.sh" test2 external-test

Upvotes: 4

Raman Garg
Raman Garg

Reputation: 91

SESSION=$(aws sts assume-role \
--role-arn arn:aws:iam::123456789012:role/MyAssumedRole \
--role-session-name MySessionName \
--query "Credentials.[AccessKeyId,SecretAccessKey,SessionToken]" \
--output text)

export AWS_ACCESS_KEY_ID=$(echo $SESSION | cut -d' ' -f1)
export AWS_SECRET_ACCESS_KEY=$(echo $SESSION | cut -d' ' -f2)
export AWS_SESSION_TOKEN=$(echo $SESSION | cut -d' ' -f3)

Upvotes: 1

Sameer Jain
Sameer Jain

Reputation: 11

based on Nev Stokes's answer if you want to add credentials to a file

using printf

printf "
[ASSUME-ROLE]
aws_access_key_id = %s
aws_secret_access_key = %s
aws_session_token = %s
x_security_token_expires = %s" \
    $(aws sts assume-role --role-arn "arn:aws:iam::<acct#>:role/<role-name>" \
      --role-session-name <session-name> \
      --query "Credentials.[AccessKeyId,SecretAccessKey,SessionToken,Expiration]" \
      --output text) >> ~/.aws/credentials

if you prefere awk

aws sts assume-role \
--role-arn "arn:aws:iam::<acct#>:role/<role-name>" \
--role-session-name <session-name> \
--query "Credentials.[AccessKeyId,SecretAccessKey,SessionToken,Expiration]" \
--output text | awk '
BEGIN {print "[ROLE-NAME]"} 
{ print "aws_access_key_id = " $1 } 
{ print "aws_secret_access_key = " $2 } 
{ print "aws_session_token = " $3 } 
{ print "x_security_token_expires = " $4}' >> ~/.aws/credentials

to update credentials in ~/.aws/credentials file run blow sed command before running one of the above command.

sed -i -e '/ROLE-NAME/,+4d' ~/.aws/credentials

Upvotes: 1

Bharat  Jain
Bharat Jain

Reputation: 161

Incase anyone wants to use credential file login:

#!/bin/bash

# Replace the variables with your own values
ROLE_ARN=<role_arn>
PROFILE=<profile_name>
REGION=<region>

# Assume the role
TEMP_CREDS=$(aws sts assume-role --role-arn "$ROLE_ARN" --role-session-name "temp-session" --output json)

# Extract the necessary information from the response
ACCESS_KEY=$(echo $TEMP_CREDS | jq -r .Credentials.AccessKeyId)
SECRET_KEY=$(echo $TEMP_CREDS | jq -r .Credentials.SecretAccessKey)
SESSION_TOKEN=$(echo $TEMP_CREDS | jq -r .Credentials.SessionToken)

# Put the information into the AWS CLI credentials file
aws configure set aws_access_key_id "$ACCESS_KEY" --profile "$PROFILE"
aws configure set aws_secret_access_key "$SECRET_KEY" --profile "$PROFILE"
aws configure set aws_session_token "$SESSION_TOKEN" --profile "$PROFILE"
aws configure set region "$REGION" --profile "$PROFILE"

# Verify the changes have been made
aws configure list --profile "$PROFILE"

Upvotes: 2

Nev Stokes
Nev Stokes

Reputation: 9779

No jq, no eval, no multiple exports - using the printf built-in (i.e. no credential leakage through /proc) and command substitution:

export $(printf "AWS_ACCESS_KEY_ID=%s AWS_SECRET_ACCESS_KEY=%s AWS_SESSION_TOKEN=%s" \
$(aws sts assume-role \
--role-arn arn:aws:iam::123456789012:role/MyAssumedRole \
--role-session-name MySessionName \
--query "Credentials.[AccessKeyId,SecretAccessKey,SessionToken]" \
--output text))

Upvotes: 255

Greg Swallow
Greg Swallow

Reputation: 181

Arcones's answer is good but here's a way that doesn't require jq:

eval $(aws sts assume-role \
 --role-arn arn:aws:iam::012345678901:role/TrustedThirdParty \
 --role-session-name=test \
 --query 'join(``, [`export `, `AWS_ACCESS_KEY_ID=`, 
 Credentials.AccessKeyId, ` ; export `, `AWS_SECRET_ACCESS_KEY=`,
 Credentials.SecretAccessKey, `; export `, `AWS_SESSION_TOKEN=`,
 Credentials.SessionToken])' \
 --output text)

Upvotes: 16

letscloud
letscloud

Reputation: 105

I have had the same problem and I managed using one of the runtimes that the CLI served me.

Once obtained the credentials I used this approach, even if not so much elegant (I used PHP runtime, but you could use what you have available in your CLI):

- export AWS_ACCESS_KEY_ID=`php -r 'echo json_decode(file_get_contents("credentials.json"))->Credentials->AccessKeyId;'`
- export AWS_SECRET_ACCESS_KEY=`php -r 'echo json_decode(file_get_contents("credentials.json"))->Credentials->SecretAccessKey;'`
- export AWS_SESSION_TOKEN=`php -r 'echo json_decode(file_get_contents("credentials.json"))->Credentials->SessionToken;'`

where credentials.json is the output of the assumed role:

aws sts assume-role --role-arn "arn-of-the-role" --role-session-name "arbitrary-session-name" > credentials.json

Obviously this is just an approach, particularly helping in case of you are automating the process. It worked to me, but I don't know if it's the best. For sure not the most linear.

Upvotes: 2

Arcones
Arcones

Reputation: 4662

Finally, a colleague shared with me this awesome snippet that gets the work done in one go:

eval $(aws sts assume-role --role-arn arn:aws:iam::123456789123:role/myAwesomeRole --role-session-name test | jq -r '.Credentials | "export AWS_ACCESS_KEY_ID=\(.AccessKeyId)\nexport AWS_SECRET_ACCESS_KEY=\(.SecretAccessKey)\nexport AWS_SESSION_TOKEN=\(.SessionToken)\n"')

Apart from the AWS CLI, it only requires jq which is usually installed in any Linux Desktop.

Upvotes: 70

Related Questions