Multiple AWS accounts and CLI

trexinc

Alex Yaroslavsky

Posted on July 18, 2020

Multiple AWS accounts and CLI

After following this guide you will able to easily and seamlessly switch between multiple AWS accounts and roles (with or without Okta) using the CLI.


Prerequisites:

Check out the first article in the series for requirements and initial configuration.


How To:

The following instructions are meant to be used in Linux or WSL, tested with Ubuntu.

Configure non Okta accounts

aws configure --profile profile
aws configure --profile multi-role-profile

Configure Okta accounts

Create a file ~/.okta-aws with the following contents:

[okta-profile]
username = <username>
factor = OKTA
app-link = https://<your-company>.okta.com/<app-link>
base-url = <your-company>.okta.com
duration = 3600

[okta-multi-role-profile]
username = <username>
factor = OKTA
app-link = https://<your-company>.okta.com/<app-link>
base-url = <your-company>.okta.com
duration = 3600

Initialize the profiles:

okta-awscli --okta-profile okta-profile --profile okta-profile
okta-awscli --okta-profile okta-multi-role-profile --profile okta-multi-role-profile

Configure accounts with multiple roles

Some accounts might use role switching, add similar sections to ~/.aws/credentials per role (notice that source_profile points to a previously defined profile):

[multi-role-profile-role1]
role_arn = <role-arn>
source_profile = multi-role-profile

[okta-multi-role-profile-role1]
role_arn = <role-arn>
source_profile = okta-multi-role-profile

Associate EKS clusters with profiles

Run the following per EKS cluster that you want to have kubectl access to, <profile-name> is a name of the AWS profile defined above that has permissions for this EKS cluster:

aws --profile <profile-name> eks update-kubeconfig --name <eks-cluster-name>

Create scripts for fast account switching

The scripts switch to the relevant AWS account, point kubectl to the relevant cluster, and set a default kubectl namespace.
Create one script file per profile, and place it in your home directory.

File okta-multi-role-profile-role1:

export AWS_DEFAULT_PROFILE=okta-multi-role-profile-role1
kubectl config use-context <eks-cluster-arn>
kubectl config set-context --current --namespace=<namespace>
aws sts get-caller-identity
if [[ $PS1 != *"AWS_DEFAULT_PROFILE"* ]]; then
  PS1=\(\$AWS_DEFAULT_PROFILE\)$PS1
fi
echo "Switched to okta-multi-role-profile-role1"

Switch between accounts

To quickly switch between accounts just do the following:
source <profile-file>

For example:
source okta-multi-role-profile-role1

💖 💪 🙅 🚩
trexinc
Alex Yaroslavsky

Posted on July 18, 2020

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related

AWS CLI with Okta
aws AWS CLI with Okta

July 13, 2020