-
Notifications
You must be signed in to change notification settings - Fork 0
/
assume_role.sh
executable file
·92 lines (77 loc) · 1.55 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
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
#!/usr/bin/env bash
# A script to be sourced to automate assume role. Use -u for unassume role.
usage() {
echo "Usage: . $0 ROLE [-u]"
return
}
validate_role() {
if ! grep -Eq "arn:aws:iam::[0-9]{12}:role/.+" <<< "$role" ; then
echo "Your role $role looks wrong"
return 1
fi
return 0
}
get_caller_identity() {
printf "Your new role:\n"
(set -x ; aws sts get-caller-identity)
}
_assume_role() {
(set -x ; aws sts assume-role \
--role-arn "$role" \
--role-session-name "Session" \
--output "json")
}
assume_role() {
read -r \
AWS_ACCESS_KEY_ID \
AWS_SECRET_ACCESS_KEY \
AWS_SECURITY_TOKEN \
<<< "$(
_assume_role | jq -r '
.Credentials
| [
.AccessKeyId,
.SecretAccessKey,
.SessionToken
]
| join(" ")'
)"
export \
AWS_ACCESS_KEY_ID \
AWS_SECRET_ACCESS_KEY \
AWS_SECURITY_TOKEN
get_caller_identity
}
unassume_role() {
printf "Resuming original role\n"
unset \
AWS_ACCESS_KEY_ID \
AWS_SECRET_ACCESS_KEY \
AWS_SECURITY_TOKEN
get_caller_identity
}
main() {
if [[ "$1" = "-h" ]] ; then
usage
elif [[ -z "$1" ]] ; then
usage
elif [[ "$1" = "-u" ]] ; then
unassume_role
else
role="$1"
validate_role && \
assume_role
fi
}
_is_sourced() {
[[ -n "$ZSH_EVAL_CONTEXT" && "$ZSH_EVAL_CONTEXT" =~ :file$ ]] || [[ "$0" != "${BASH_SOURCE[0]}" ]]
}
if _is_sourced ; then
main "$@"
elif [[ "$1" = "-h" ]] ; then
usage
exit 1
else
echo "This script should be sourced not executed"
usage
fi