Skip to content

Instantly share code, notes, and snippets.

@caruccio
Created May 17, 2024 11:53
Show Gist options
  • Save caruccio/4b017a921944378a729f3d704e319212 to your computer and use it in GitHub Desktop.
Save caruccio/4b017a921944378a729f3d704e319212 to your computer and use it in GitHub Desktop.
AWS Assume Role
#!/bin/bash
#
# Install:
# $ echo 'source ~/bin/aws-assume-role' >> ~/.bashrc
#
# Usage:
# $ aws-assume-role [name]
#
# Prerequisite:
# Create an IAM role like this in the account you what access:
#
# Maximum session duration: 12h
# Permissions policies: AdministratorAccess
# Trusted relationships:
# {
# "Version": "2012-10-17",
# "Statement": [
# { "Effect": "Allow", "Action": "sts:AssumeRole", "Principal": { "AWS": "arn:aws:iam::975877104335:root" } }
# ]
# }
function aws-list-profiles()
{
sed -ne 's/^\s*\[\(.*\)\]/\1/p' ~/.aws/config
}
function aws-assume-role()
{
local ROLE=
local AWS_ACCOUNT_ID=""
if [[ "$1" =~ [0-9]+ ]]; then
echo Using Account ID $1
AWS_ACCOUNT_ID=$1
else
local AWS_TARGET_PROFILE=$(aws-list-profiles | fzf --select-1 --reverse --exact ${1:+--query "$1"})
if [ -z "$AWS_TARGET_PROFILE" ]; then
return
fi
if ! grep -q "^\[$AWS_TARGET_PROFILE]" ~/.aws/config &>/dev/null; then
echo "Missing or invalid Account ID: $AWS_TARGET_PROFILE"
return 1
fi
echo Using Profile: $AWS_TARGET_PROFILE
ROLE=$(sed -ne "/^\\[$AWS_TARGET_PROFILE]/,/^\\[/p" ~/.aws/config | sed -ne 's/\s*role_arn\s*=\s*\(.*\)/\1/p')
echo Using Role: $ROLE
fi
if [ -z "$ROLE" ]; then
ROLE=arn:aws:iam::${AWS_ACCOUNT_ID}:role/getupcloud
elif [ -z "$AWS_ACCOUNT_ID" ]; then
AWS_ACCOUNT_ID=$(cut -d: -f5 <<<$ROLE)
fi
if ! [[ "$ROLE" =~ arn:aws:iam::[0-9]+:role/[a-z0-9]+ ]]; then
echo Invalid role: $ROLE
return 1
fi
local AWS_PROFILE=${AWS_PROFILE:-default}
echo -n "Current identity ($AWS_PROFILE): "
aws sts get-caller-identity --profile $AWS_PROFILE | jq -r .Arn
local session_name_suffix=${AWS_TARGET_PROFILE// /-}
session_name_suffix=${session_name_suffix//:/-}
local CREDENTIALS=$(
AWS_SESSION_TOKEN='' aws sts assume-role ${AWS_PROFILE:+--profile=$AWS_PROFILE} --role-arn "$ROLE" --role-session-name "AWSCLI-Session-${session_name_suffix}" --duration-seconds=$((12*60*60))
)
local ROLE_ACCESS_KEY_ID="$(jq -r .Credentials.AccessKeyId <<<$CREDENTIALS)"
local ROLE_SECRET_KEY="$(jq -r .Credentials.SecretAccessKey <<<$CREDENTIALS)"
local ROLE_SESSION_TOKEN="$(jq -r .Credentials.SessionToken <<<$CREDENTIALS)"
export AWS_ACCOUNT_ID="$AWS_ACCOUNT_ID"
export AWS_ACCESS_KEY_ID=$ROLE_ACCESS_KEY_ID
export AWS_SECRET_ACCESS_KEY=$ROLE_SECRET_KEY
export AWS_SESSION_TOKEN=$ROLE_SESSION_TOKEN
echo -n 'Assuming role: '
aws sts get-caller-identity | jq -r .Arn
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment