forked from civisanalytics/iam-role-injector
-
Notifications
You must be signed in to change notification settings - Fork 0
/
assume_role.sh
executable file
·76 lines (67 loc) · 2.58 KB
/
assume_role.sh
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
# USAGE:
# requires 4 args, needs to be run with source to get exported variables to stick
# source assume_role.sh {sourceAccountNumber} {username} {destinationAccountNumber} {rolename}
sourceAccountNumber=$1
username=$2
destinationAccountNumber=$3
rolename=$4
aws_profile=${5:-default}
if [ -n "$destinationAccountNumber" ] && [ -n "$sourceAccountNumber" ] && [ -n "$rolename" ] && [ -n "$username" ]; then
if [ -z "$AWS_ACCESS_KEY_ID" ] && [ -z "$AWS_SECRET_ACCESS_KEY" ]; then
AWSprofile="--profile ${aws_profile}"
elif [ "default" != "${aws_profile}" ]; then
AWSprofile="--profile ${aws_profile}"
else
AWSprofile=
fi
echo "Enter MFA token code:"
read tokenCode
unset AWS_SECURITY_TOKEN
unset AWS_SESSION_TOKEN
if [ -z "$AWS_ENV_VARS" ]; then
if [ -z "$AWS_SECRET_ACCESS_KEY" ]; then
export AWS_ENV_VARS="True"
elif [ -z "$OG_AWS_SECRET_ACCESS_KEY" ]; then
export OG_AWS_SECRET_ACCESS_KEY=$AWS_SECRET_ACCESS_KEY
export OG_AWS_ACCESS_KEY_ID=$AWS_ACCESS_KEY_ID
else
export AWS_SECRET_ACCESS_KEY=$OG_AWS_SECRET_ACCESS_KEY
export AWS_ACCESS_KEY_ID=$OG_AWS_ACCESS_KEY_ID
fi
else
unset AWS_SECRET_ACCESS_KEY
unset AWS_ACCESS_KEY_ID
fi
roleArn="arn:aws:iam::"
roleArn+="$destinationAccountNumber"
roleArn+=":role/"
roleArn+="$rolename"
serialArn="arn:aws:iam::"
serialArn+="$sourceAccountNumber"
serialArn+=":mfa/"
serialArn+="$username"
commandResult=" "
commandResult+=$(aws sts assume-role --output json \
${AWSprofile} \
--role-arn $roleArn \
--role-session-name iam-role-injector \
--serial-number $serialArn \
--query 'Credentials.[SecretAccessKey, SessionToken, AccessKeyId]' \
--token-code $tokenCode)
size=${#commandResult}
if (( $size > 5 )); then
commandResult1=$(echo "$commandResult" | sed '5d' | sed '1d' | tr -d '\040\011\012\015' | sed 's/\"//g')
echo "You have assumed the $rolename role successfully."
arg1=$(echo "$commandResult1" | cut -d "," -f1)
export AWS_SECRET_ACCESS_KEY=$arg1
arg2=$(echo "$commandResult1" | cut -d "," -f2)
# Set AWS_SESSION_TOKEN and AWS_SECURITY_TOKEN for backwards compatibility
# See: http://boto3.readthedocs.org/en/latest/guide/configuration.html
export AWS_SECURITY_TOKEN=$arg2
export AWS_SESSION_TOKEN=$arg2
arg3=$(echo "$commandResult1" | cut -d "," -f3)
export AWS_ACCESS_KEY_ID=$arg3
fi
else
echo "Usage: source assume_role.sh {sourceAccountNumber} {username} {destinationAccountNumber} {rolename} {profileName}"
fi