Switch Roles in AWS Using the CLI.

PhilPhil
4 min read

Introduction:

Managing multiple AWS accounts can be a daunting task, especially when it comes to switching between different roles and managing resources across accounts and regions. By using Management Console it can be time-consuming and inefficient. That's where the AWS CLI comes in. In this article, we'll show you how to switch roles in AWS using the CLI.

Pre-conditions:

  • You must have at least two AWS accounts.

  • You need to create an IAM ROLE on the account you want to switch to.

  • You need to generate an Access Key ID and Secret Access Key.

  • The AWS CLI environment must already be installed.

CASE 1: MFA Not Enabled in the destination account

  1. Open the CLI and type aws configure and provide your necessary credentials.
ubuntu@ubuntu-user ~ % aws configure
AWS Access Key ID [****************STEX]:XXXXXXXXXXXXXXXXXXXX
AWS Secret Access Key [****************8MNX]: ZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZ
Default region name [ap-northeast-1]: ap-northeast-1
Default output format [json]: json
  1. After you set up your AWS CLI you’ll have your credentials stored in the ~/.aws/credentials file which includes your access keys and secret keys to log you into your accounts.
[default]
aws_access_key_id = XXXXXXXXXXXXXXXXXXXX
aws_secret_access_key = ZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZ

and your ~/.aws/config file will look like this.

[default]
region = ap-northeast-1
output = json
  1. Now open the ~/.aws/config file and add the ARN of the role you want to assume. In this case, the AWS account IDs for the roles are "152023501972" and "991488085344" and role names are RoleForOtherAccounts and ReadOnlyAccessRole. Make sure to save the changes once you've added the necessary information."
[default]
region = ap-northeast-1
output = json

[profile step-user]
role_arn=arn:aws:iam::152023501972:role/RoleForOtherAccounts
source_profile=default

[profile sandbox]
role_arn=arn:aws:iam::991488085344:role/ReadOnlyAccessRole
source_profile=default

Note that you need to create an IAM Role and assign the necessary permissions to the role on the account you want to switch into.

  1. Type the below command in your current account and list the s3 buckets.
ubuntu@ubuntu-user ~ % aws s3 ls
2023-07-22 13:15:30 my-aws-and-s3-config-bucket
  1. Type the same command but use the --profile option and the profile name that we configured above.
ubuntu@ubuntu-user ~ % aws s3 ls --profile step-user
2023-07-22 13:16:16 test-prod-bucket-ap
ubuntu@ubuntu-user ~ % aws s3 ls --profile sandbox
2023-07-22 13:16:20 member-config-bucket

you can view the s3 bucket of both AWS accounts. Additionally, you can switch to multiple account roles by simply modifying the ~/.aws/config file. However, it's important to note that you need to create an IAM Role and assign the necessary permissions to the role on the account you want to switch to.

CASE 2: MFA Enabled in the destination account

Keep in mind that if the IAM Role trust policy includes an MFA condition, you won't be able to list the resources of the account that you're switching into. This restriction is due to the added security measures of MFA. The IAM Role trust policy specifies which entities are allowed to assume the role and under what conditions they are allowed to do so. IAM Role trust policy looks like this:

{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Effect": "Allow",
            "Principal": {
                "AWS": "arn:aws:iam::{Account}:user/{UserName}"
            },
            "Action": "sts:AssumeRole",
            "Condition": {
                "Bool": {
                    "aws:MultiFactorAuthPresent": "true"
                }
            }
        }
    ]
}

if you attempt to execute the command using the --profile option, you may receive the following error message:

ubuntu@ubuntu-user ~ % aws s3 ls --profile sandbox
An error occurred (AccessDenied) when calling the AssumeRole operation:
User: arn:aws:iam::Your_Account_ID:mfa/IAM_USERNAME is not authorized to perform:
sts:AssumeRole on resource: arn:aws:iam::991488085344:role/ReadOnlyAccessRole
  1. To enable MFA (multi-factor authentication) for your current account in AWS, open the ~/.aws/config file and add the 'mfa_serial' value. If you're unsure of where to find your MFA identifier, sign in to the AWS Management Console, click on your username in the upper-right corner, and select 'My Security Credentials'. From there, you can locate your MFA identifier and copy it to the appropriate field in the config file.
[default]
region = ap-northeast-1
output = json

[profile step-user]
role_arn=arn:aws:iam::152023501972:role/RoleForOtherAccounts
source_profile=default
mfa_serial = arn:aws:iam::Your_Account_ID:mfa/IAM_USERNAME

[profile sandbox]
role_arn=arn:aws:iam::991488085344:role/ReadOnlyAccessRole
source_profile=default
mfa_serial = arn:aws:iam::Your_Account_ID:mfa/IAM_USERNAME
  1. Now run the following command and try to use --profile option for each account.
ubuntu@ubuntu-user ~ % aws s3 ls --profile step-user
Enter MFA code for arn:aws:iam::Your_Account_ID:mfa/IAM_USERNAME:
[Enter the six digit MFA Token Code]
2023-07-22 13:16:16 test-prod-bucket-ap

ubuntu@ubuntu-user ~ % aws s3 ls --profile sandbox
Enter MFA code for arn:aws:iam::Your_Account_ID:mfa/IAM_USERNAME:
[Enter the six digit MFA Token Code]
2023-07-22 13:16:20 member-config-bucket

as you can see the output of the command is displaying the s3 buckets for each account.

Conclusion:

To switch roles among multiple AWS accounts, you can use the --profile option in the AWS CLI. This method is easy to use and relies on pre-configured profiles to switch between accounts and roles.

By using this method, you can switch roles among multiple AWS accounts. However, switching roles manually using the --profile option might be time-consuming, especially if you have numerous AWS accounts. Therefore, to automate role switching, you can use scripts or automation workflows that use the aws sts assume-role command to generate temporary security credentials for the target role.

0
Subscribe to my newsletter

Read articles from Phil directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Phil
Phil

Hello and welcome to my blog! I am a passionate professional with a diverse background in Quality Assurance (QA) and System Engineering, and I am currently working as an AWS Engineer. While my experience in AWS spans a relatively short period, my enthusiasm for Cloud Technology is unwavering. Throughout my career, I have gained hands-on experience in a wide range of AWS services, both through my professional work and dedicated self-study. This practical exposure has provided me with valuable insights and deepened my understanding of leveraging AWS to build robust and scalable solutions. On this blog, I aim to share my experiences, insights, and practical guidance on AWS services and their application in real-world scenarios. Whether you are a cloud enthusiast, an aspiring AWS professional, or someone simply looking to deepen your understanding of cloud technology, I invite you to join me on this exciting journey. Thank you for visiting my blog, and I look forward to connecting and engaging with you as we delve into the world of AWS and cloud technology.