Created
October 25, 2024 15:36
-
-
Save abraithwaite/17842aa2031330783971661a5a764b4e to your computer and use it in GitHub Desktop.
A script to run commands as a given profile using IAM Identity Center (SSO) profiles.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/bin/bash -e | |
# aws-run | |
# Usage: aws-run <profile-name> -- <command> | |
# | |
# To use this script with AWS IAM Identity Center user credentials, follow this guide: | |
# https://docs.aws.amazon.com/singlesignon/latest/userguide/howtogetcredentials.html#how-to-get-temp-credentials-automatic | |
# | |
# When asked for the CLI profile name, choose one that you don't mind typing | |
# every time you run a command. | |
# | |
# Then run this script with the profile name and the command you want to execute. | |
if [ "$#" -lt 3 ]; then | |
echo "Usage: $(basename $0) <profile-name> -- <command>" | |
exit 1 | |
fi | |
PROFILE=$1 | |
shift # Remove profile from args | |
if [ "$1" != "--" ]; then | |
echo "Error: Missing -- separator" | |
echo "Usage: $(basename $0) <profile-name> -- <command>" | |
exit 1 | |
fi | |
shift # Remove -- from args | |
# Verify the profile exists and credentials are valid | |
aws sts get-caller-identity --profile "$PROFILE" > /dev/null 2>&1 | |
if [ $? -ne 0 ]; then | |
echo "Error: Failed to get credentials. Make sure:" >&2 | |
echo "1. The profile '$PROFILE' exists" >&2 | |
echo "2. You're logged in (run 'aws sso login --profile $PROFILE' if needed)" >&2 | |
exit 1 | |
fi | |
# Get the credentials using AWS CLI | |
CREDS=$(aws configure export-credentials --profile "$PROFILE" --format env 2>/dev/null) | |
if [ $? -ne 0 ]; then | |
echo "Error: Failed to export credentials" >&2 | |
exit 1 | |
fi | |
# Get the region if set in the profile | |
REGION=$(aws configure get region --profile "$PROFILE") | |
# Execute the command with the credentials | |
( | |
if [ -n "$REGION" ]; then | |
export AWS_REGION="$REGION" | |
export AWS_DEFAULT_REGION="$REGION" | |
fi | |
eval "$CREDS" | |
exec "$@" | |
) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment