public infrastructure tools
This repository provides a Bash script
(get-aws-subaccount-session.sh) to establish
an AWS CLI session with a subaccount using
role assumption. It allows users to securely
switch AWS accounts using MFA authentication,
ensuring temporary access without storing
permanent credentials.
The script:
- Assumes an IAM role in a subaccount using AWS STS.
- Requires MFA authentication to generate temporary session tokens.
- Supports manual or automated MFA entry (if a TOTP secret is stored).
- Ensures AWS credentials persist in the terminal session.
Before using this script, ensure that:
- You have AWS CLI installed and configured with your base account credentials.
- Your IAM user has permissions to assume a role in the subaccount.
- You have an MFA device registered for authentication.
- Run the Script (Must Be Sourced)
source aws-cli/get-aws-subaccount-session.sh-
Enter MFA Code When prompted, enter your MFA token to authenticate.
-
Verify the Session After running the script, check if your AWS CLI session is active:
aws sts get-caller-identityIf successful, you should see the assumed role and account ID.
AWS STS tokens expire after a set duration. If your session expires:
- Unset the old session credentials:
unset AWS_SESSION_TOKEN AWS_SECRET_ACCESS_KEY AWS_ACCESS_KEY_ID- Re-run the script to assume the role again:
. aws-cli/get-aws-subaccount-session.sh
You can modify the script to adjust the following settings:
- Session duration: Change the
aws_target_subaccount_session_secondsvariable to increase or decrease the session time (default is 3600 seconds). - Target AWS account: Update
aws_target_subaccount_idto switch to a different subaccount. - IAM Role: Change
aws_target_subaccount_roleif your organization uses different role names.
These values can be found in the "AWS CLI Config Import" section inside the script.
If you want to automate MFA token entry, save your MFA secret key in the file:
~/.aws/mfa/isc-login_totpThen, modify the script to use oathtool for TOTP generation.
- AWS credentials are temporary and expire after the defined session duration (up to one hour).
- You can modify the target subaccount, role, and session time inside the script.
- This script does not modify AWS CLI configuration files—it only sets temporary environment variables.