Skip to content

Instantly share code, notes, and snippets.

@sebsto
Last active December 12, 2024 10:06
Show Gist options
  • Save sebsto/6f7c9eaf500ac11756a86babde75ffc0 to your computer and use it in GitHub Desktop.
Save sebsto/6f7c9eaf500ac11756a86babde75ffc0 to your computer and use it in GitHub Desktop.
Assume Root on AWS member accounts
#!/bin/bash
AWS_ACCOUNT_ID=012345678901
# 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 > 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