Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save AyhanSetirekli/26117af8bb41a011185ed0ebb60256b3 to your computer and use it in GitHub Desktop.
Save AyhanSetirekli/26117af8bb41a011185ed0ebb60256b3 to your computer and use it in GitHub Desktop.
Assume Root on AWS member accounts
#!/bin/bash
# Check if AWS_ACCOUNT_ID is provided as first argument
if [ -z "$1" ]; then
read -p "Please enter AWS Account ID: " AWS_ACCOUNT_ID
if [ -z "$AWS_ACCOUNT_ID" ]; then
echo "Error: AWS Account ID is required."
exit 1
fi
else
AWS_ACCOUNT_ID="$1"
fi
# Validate AWS_ACCOUNT_ID format (12 digits)
if ! [[ "$AWS_ACCOUNT_ID" =~ ^[0-9]{12}$ ]]; then
echo "Error: AWS Account ID must be a 12-digit number."
exit 1
fi
# Check if jq is installed
if ! command -v jq &> /dev/null; then
echo "Error: jq is not installed. Please install jq to parse JSON."
exit 1
fi
# ask for temporary credentials for the target account
aws sts assume-root --target-principal ${AWS_ACCOUNT_ID} \
--task-policy-arn arn=arn:aws:iam::aws:policy/root-task/IAMAuditRootUserCredentials \
--output json > credentials.json
# Check if credentials.json file exists
if [ ! -f "credentials.json" ]; then
echo "Error: credentials.json file not found."
exit 1
fi
# Extract credentials from JSON and set environment variables
export AWS_ACCESS_KEY_ID=$(jq -r '.Credentials.AccessKeyId' credentials.json)
export AWS_SECRET_ACCESS_KEY=$(jq -r '.Credentials.SecretAccessKey' credentials.json)
export AWS_SESSION_TOKEN=$(jq -r '.Credentials.SessionToken' credentials.json)
# Verify if the variables are set
if [ -z "$AWS_ACCESS_KEY_ID" ] || [ -z "$AWS_SECRET_ACCESS_KEY" ] || [ -z "$AWS_SESSION_TOKEN" ]; then
echo "Error: Failed to extract one or more credentials from the JSON."
exit 1
fi
# Print success message
echo "AWS credentials have been successfully set as environment variables."
echo "You can now use these credentials in your AWS CLI or SDK applications."
# Run an action as root on the member account
aws sts get-caller-identity
# Reset environment variables
export AWS_ACCESS_KEY_ID=
export AWS_SECRET_ACCESS_KEY=
export AWS_SESSION_TOKEN=
# do not leave the credentials file behind
rm credentials.json
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment