Last active
January 25, 2019 11:39
-
-
Save vatshat/9d3909901d9bdb6e87ccc00e8549bffa to your computer and use it in GitHub Desktop.
How to use STS temporary keys to authenticate
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/bin/bash | |
############################################################################## | |
# assume role and populate in environment variables # | |
############################################################################## | |
#using meta data | |
url="http://169.254.169.254/latest/meta-data/" | |
iam="iam/security-credentials/" | |
security_credentials=$(curl -s "$url$iam") | |
iam_meta_data=$(curl -s "$url$iam$security_credentials") | |
export AWS_ACCESS_KEY_ID=$(jq --raw-output ".AccessKeyId" <<< $iam_meta_data) | |
export AWS_SECRET_ACCESS_KEY=$(jq --raw-output ".SecretAccessKey" <<< $iam_meta_data) | |
export AWS_SESSION_TOKEN=$(jq --raw-output ".Token" <<< $iam_meta_data) | |
export AWS_DEFAULT_REGION=$(curl -s "$url/placement/availability-zone" | sed 's/[a-z]$//') | |
#using STS | |
assumed_role=$(aws sts assume-role --role-arn arn:aws:iam::037559324442:role/ec2-cli-access --role-session-name "thabile-laptop-cli") | |
echo $assumed_role | jq '.AssumedRoleUser | keys as $k | {"\($k[1])":.AssumedRoleId}' | |
export AWS_ACCESS_KEY_ID=$(jq --raw-output ".Credentials.AccessKeyId" <<< $assumed_role) | |
export AWS_SECRET_ACCESS_KEY=$(jq --raw-output ".Credentials.SecretAccessKey" <<< $assumed_role) | |
export AWS_SESSION_TOKEN=$(jq --raw-output ".Credentials.SessionToken" <<< $assumed_role) | |
export AWS_DEFAULT_REGION=eu-west-1 | |
############################################################################## | |
# get authenticate with MFA and populate in environment variables # | |
############################################################################## | |
read token&&temp=$(aws sts get-session-token --serial-number arn:aws:iam::037559324442:mfa/mfa --token-code $token)&&export AWS_ACCESS_KEY_ID=$(echo $temp | jq -r '.Credentials.AccessKeyId')&&export AWS_SECRET_ACCESS_KEY=$(echo $temp | jq -r '.Credentials.SecretAccessKey')&&export AWS_SESSION_TOKEN=$(echo $temp | jq -r '.Credentials.SessionToken') |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment