-
Notifications
You must be signed in to change notification settings - Fork 1
/
aws_run_as.sh
88 lines (74 loc) · 2.48 KB
/
aws_run_as.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
76
77
78
79
80
81
82
83
84
85
86
87
88
#!/usr/bin/env bash
set -x
usage="Usage: awsas [--debug] [--profie aprofile] role-name <aws subcommand and options>. \nA dynamic version of --profile. Whereas --profile requires setting up configuration, awsas allows you to assume roles without setup. \nEg. awsas myrole sts get-caller-identity should return identity for myrole\n"
function unset_aws() {
unset AWS_ACCESS_KEY_ID
unset AWS_SECRET_ACCESS_KEY
unset AWS_SESSION_TOKEN
}
function awsas () {
if [ $# -eq 0 ]; then
printf "${usage}"
exit 0
fi
debug=""
if [[ $1 == "--debug" ]]; then
debug="DEBUG"
shift
echo "args: $@"
fi
unset_aws
if [[ $1 == "--profile" ]]; then
shift
export profile=$1
shift
if [[ $debug == "DEBUG" ]]; then
echo "Setting profile to $profile"
fi
account_id=`aws --profile $profile sts get-caller-identity | jq '.Account' | sed 's|\"||g'`
role=$1
shift
role_arn=""
if [[ $1 == "--path" ]]; then
shift
path=$1
shift
role_arn="arn:aws:iam::$account_id:role$path$role"
else
role_arn="arn:aws:iam::$account_id:role/$role"
fi
if [[ $debug == "DEBUG" ]]; then
echo "assuming role arn $role_arn"
fi
creds=`aws --profile $profile sts assume-role --role-arn $role_arn --role-session-name $role`
if [[ $debug == "DEBUG" ]]; then
echo "`echo ${creds} | jq '.AssumedRoleUser.Arn'`"
fi
else
echo $@
role=$1
shift
echo "role: $role"
role_arn=""
account_id=`aws sts get-caller-identity | jq '.Account' | sed 's|\"||g'`
if [[ $1 == "--path" ]]; then
shift
path=$1
shift
role_arn="arn:aws:iam::$account_id:role$path$role"
else
role_arn="arn:aws:iam::$account_id:role/$role"
fi
if [[ $debug == "DEBUG" ]]; then
printf "Using account $account_id \n Calling aws sts assume-role --role-arn $role_arn --role-session-name $role \n"
printf "Remaining args: $@ \n"
fi
creds=`aws sts assume-role --role-arn $role_arn --role-session-name $role`
fi
export AWS_ACCESS_KEY_ID=`echo ${creds} | jq '.Credentials.AccessKeyId' | sed 's|\"||g'`
export AWS_SECRET_ACCESS_KEY=`echo ${creds} | jq '.Credentials.SecretAccessKey' | sed 's|\"||g'`
export AWS_SESSION_TOKEN=`echo ${creds} | jq '.Credentials.SessionToken' | sed 's|\"||g'`
aws "$@"
unset_aws
}
awsas "$@"