bash functions to help run aws-cli commands across roles in multiple accounts with MFA
For more background information and explanation for how to use this, please read this blog post:
You didn't read that, did you?
Ok, here are the quick notes I use to set this up and use it in my accounts.
Clone this repo wherever you like:
mkdir -p $HOME/src && ( cd $HOME/src && git clone firstname.lastname@example.org:alestic/aws-cli-multi-account-sessions.git )
Add something like this to
$HOME/.bashrc using the values for
mfa_serial from your aws-cli config file.
# https://github.com/alestic/aws-cli-multi-account-sessions test -x $HOME/src/aws-cli-multi-account-sessions/functions.sh && source $HOME/src/aws-cli-multi-account-sessions/functions.sh export AWS_SESSION_SOURCE_PROFILE=default export AWS_SESSION_MFA_SERIAL=arn:aws:iam::YOUR_ACCOUNT:mfa/YOUR_USER
Then load it up in your current shell:
Specify the role you can assume in all accounts:
role="admin" # Yours might be called "OrganizationAccountAccessRole"
Get a list of all accounts in the AWS Organization:
accounts=$(aws organizations list-accounts \ --output text \ --query 'Accounts.[JoinedTimestamp,Status,Id,Email,Name]' | grep ACTIVE | sort | cut -f3) # just the ids echo "$accounts"
Run once to create temporary session credentials with MFA:
Iterate through AWS accounts using
aws-session-set to specify the
account/role you want to to use for running commands. Run AWS CLI
commands in that account/role by prefixing the command with
for account in $accounts; do aws-session-set $account $role || continue this_account=$(aws-session-run \ aws sts get-caller-identity \ --output text \ --query 'Account') echo "Account: $account ($this_account)" aws-session-run aws s3 ls done
Clear out bash variables holding temporary credentials:
Of course, this might not work for you if you don't have things set up quite the same way as I do. Perhaps you should go back and read the blog post above?
Eric Hammond https://twitter.com/esh
All the good in this is based on example code from Jennine Townsend. All the bad is mine.