Skip to content
bash functions to help run aws-cli commands across roles in multiple accounts with MFA
Branch: master
Clone or download
Latest commit 331dd7d Dec 30, 2019
Type Name Latest commit message Commit time
Failed to load latest commit information.
LICENSE Initial commit Dec 30, 2019 grammar Dec 30, 2019


bash functions to help run aws-cli commands across roles in multiple accounts with MFA

Blog Post

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

Add something like this to $HOME/.bashrc using the values for source_profile and mfa_serial from your aws-cli config file.

test -x $HOME/src/aws-cli-multi-account-sessions/ &&
 source $HOME/src/aws-cli-multi-account-sessions/

Then load it up in your current shell:

source $HOME/.bashrc


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 aws-session-run

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

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


All the good in this is based on example code from Jennine Townsend. All the bad is mine.

You can’t perform that action at this time.