Skip to content

Instantly share code, notes, and snippets.

@garymacindoe
Created September 3, 2019 10:16
Show Gist options
  • Save garymacindoe/79392be0e7184991e10a7cca0e488d2f to your computer and use it in GitHub Desktop.
Save garymacindoe/79392be0e7184991e10a7cca0e488d2f to your computer and use it in GitHub Desktop.
Wraps `aws sts assume-role` to launch commands in a modified environment so that it can be used with `wormhole`.
#!/bin/sh
die() {
printf '%s\n' "${1}" >&2
exit 1
}
ROLE_ARN=""
ROLE_SESSION_NAME="dev-${USER}"
EXTERNAL_ID=""
DURATION_SECONDS="900"
while :
do
case "${1}" in
--role-arn)
if [ "${2}" ]
then
ROLE_ARN="${2}"
shift
else
die 'ERROR: "--role-arn" requires a non-empty option argument'
fi
;;
--role-arn=?*)
ROLE_ARN="${1#*=}"
;;
--role-arn=)
die 'ERROR: "--role-arn" requires a non-empty option argument'
;;
--role-session-name)
if [ "${2}" ]
then
ROLE_SESSION_NAME="${2}"
shift
else
die 'ERROR: "--role-session-name" requires a non-empty option argument'
fi
;;
--role-session-name=?*)
ROLE_SESSION_NAME="${1#*=}"
;;
--role-session-name=)
die 'ERROR: "--role-session-name" requires a non-empty option argument'
;;
--external-id)
if [ "${2}" ]
then
EXTERNAL_ID="${2}"
shift
else
die 'ERROR: "--external-id" requires a non-empty option argument'
fi
;;
--external-id=?*)
EXTERNAL_ID="${1#*=}"
;;
--external-id=)
die 'ERROR: "--external-id" requires a non-empty option argument'
;;
--duration-seconds)
if [ "${2}" ]
then
DURATION_SECONDS="${2}"
shift
else
die 'ERROR: "--duration-seconds" requires a non-empty option argument'
fi
;;
--duration-seconds=?*)
DURATION_SECONDS="${1#*=}"
;;
--duration-seconds=)
die 'ERROR: "--duration-seconds" requires a non-empty option argument'
;;
--)
shift
break
;;
-?*)
die "ERROR: unknown option: ${1}"
;;
*)
break
esac
shift
done
if [ ! "${ROLE_ARN}" ]
then
die 'Error: --role-arn must be provided!'
fi
if [ "${DURATION_SECONDS}" ]
then
DURATION_SECONDS="--duration-seconds ${DURATION_SECONDS}"
fi
if [ "${EXTERNAL_ID}" ]
then
EXTERNAL_ID="--external-id ${EXTERNAL_ID}"
fi
eval exec env $(
aws sts assume-role --role-arn ${ROLE_ARN} --role-session-name ${ROLE_SESSION_NAME} ${DURATION_SECONDS} ${EXTERNAL_ID} | \
jq -Mrc '.Credentials | "AWS_ACCESS_KEY_ID=\"\(.AccessKeyId)\" AWS_SECRET_ACCESS_KEY=\"\(.SecretAccessKey)\" AWS_SESSION_TOKEN=\"\(.SessionToken)\""'
) ${@}
@garymacindoe
Copy link
Author

garymacindoe commented Sep 11, 2019

Example: wormhole mediastorage-development ./assume-role.sh --role-arn arn:aws:iam::123456789012:role/MyRole aws s3 ls

It's also possible to chain calls to assume a role that can assume another role, etc:
wormhole mediastorage-development ./assume-role.sh --role-arn arn:aws:iam::123456789012:role/MyRole ./assume-role.sh --role-arn arn:aws:iam::210987654321:role/MyOtherRole aws s3 ls

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment