Fri Dec 27 2024

Managing Multiple AWS Accounts from the Command Line

Working with multiple AWS accounts can be a necessity when you have separate projects or environments, such as development and production, each needing its own AWS account. Fortunately, AWS CLI provides a straightforward way to manage these accounts efficiently using profiles.

Setting Up Multiple AWS Profiles

Instead of juggling environment variables or creating complicated scripts to switch between accounts, you can set up AWS CLI profiles for each account. Profiles store the access credentials, region, and other configuration information.

To configure a new profile, use the following command:

aws configure --profile account1

Repeat for the second account:

aws configure --profile account2

Each aws configure command will prompt you for the AWS Access Key ID, AWS Secret Access Key, and default region. Once done, you can use these profiles in your CLI commands.

Switching Between AWS Accounts

Switching accounts is as simple as specifying the profile you want to use in your command:

aws dynamodb list-tables --profile account1
aws s3 ls --profile account2

This approach ensures that you use the correct AWS credentials associated with the account you want to manage, without having to constantly modify environment variables.

Using the Default Profile

If you frequently use one account more than others, you can set it as the default. This means you won’t need to specify the --profile parameter for each command:

By default, AWS CLI uses the profile named default. When no --profile argument is provided, the CLI defaults to using the default profile.

To set a default profile temporarily, you can use the following command in Linux or Mac OS:

export AWS_DEFAULT_PROFILE=account1
aws dynamodb list-tables

For Windows, use:

set AWS_DEFAULT_PROFILE=account1
aws s3 ls

Keep in mind this change only lasts for the duration of your session. When you close your terminal, you’ll need to set it again when reopening.

If you want a more permanent solution, consider adding the export or set command to your shell’s initialization file, such as .bashrc, .zshrc, or .bash_profile.

Summary

Managing multiple AWS accounts using the AWS CLI is simplified through the use of profiles. Not only does this method keep account information organized and separate, it also enhances security by limiting the spread of sensitive credentials across your system.

For more details on managing profiles, visit the AWS CLI Configuration Guide.