Skip to content

Instantly share code, notes, and snippets.

@limed
Last active February 15, 2019 02:03
Show Gist options
  • Save limed/74a99132b52c970d58f9257781f838a3 to your computer and use it in GitHub Desktop.
Save limed/74a99132b52c970d58f9257781f838a3 to your computer and use it in GitHub Desktop.
creates an IAM role and allows a user to do a role assumption
#!/usr/bin/env bash
set -o errexit
set -o pipefail
USERNAME=$1
ACCOUNT_ID=$(aws sts get-caller-identity --query "Account" --output text)
errexit() {
echo "$1"
exit 1
}
if [ -z "${USERNAME}" ]; then
errexit "Usage: $0 <IAM Username>"
fi
if [ -z "${ACCOUNT_ID}" ]; then
errexit "Account ID is not set"
fi
# I created an assume role policy and ran jq '.|tostring' assume-role.json
ASSUME_ROLE_POLICY="{\"Version\":\"2012-10-17\",\"Statement\":[{\"Effect\":\"Allow\",\"Principal\":{\"AWS\":\"arn:aws:iam::${ACCOUNT_ID}:user/${USERNAME}\"},\"Action\":\"sts:AssumeRole\"}]}"
## TODO: enforce mfa
STS_ASSUME="{\"Version\":\"2012-10-17\",\"Statement\":[{\"Effect\":\"Allow\",\"Action\":\"sts:AssumeRole\",\"Resource\":[\"arn:aws:iam::${ACCOUNT_ID}:role/\${aws:username}\"]}]}"
echo "Checking if IAM user exists"
aws iam get-user --user-name "${USERNAME}" || errexit "User ${USERNAME} does not exists"
echo "Checking if role exists"
#aws iam get-role --role-name "${USERNAME}"
ROLE_NAME=$(aws iam list-roles --query "Roles[?RoleName == '${USERNAME}']" --output text)
if [ -z "${ROLE_NAME}" ]; then
echo "Creating role ${USERNAME}"
aws iam create-role --role-name "${USERNAME}" --assume-role-policy-document "${ASSUME_ROLE_POLICY}"
# Sometimes IAM takes a while
sleep 2
echo "Attaching AdministratorAccess role to role ${USERNAME}"
aws iam attach-role-policy --role-name "${USERNAME}" --policy-arn "arn:aws:iam::aws:policy/AdministratorAccess"
fi
echo "Allow user ${USERNAME} to assume role"
aws iam put-user-policy --user-name "${USERNAME}" --policy-document "${STS_ASSUME}" --policy-name "sts-allow"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment