how to switch accounts in a pipeline

Dipesh Majumdar
2 min readFeb 23, 2023

--

Suppose you are already in a pipeline and you are authenticated for Account A. But there can be a requirement where you need to assume role to another account B and then again switch back to A. How do you do that? Well you need roleArn for Account B and 2 bash functions!!! you can call the first function when you want to switch to Account B and call back second function when you want to switch back.

Let’s start with few example values to make our understanding of the bash script concrete.

For account A

  • Account_id: 129030836016
  • Username: gitlab-ci (it is a system user)

For account B

  • Account_id: 229030836016
  • roleArn: is ARN of role that is present
#!/bin/bash

function set_account_b_creds() {
printf "\nsetting credentials for account b now\n"
printf "\nFirst backup your original keys\n"
echo $AWS_ACCESS_KEY_ID >AWS_ACCESS_KEY_ID_ORIGINAL
echo $AWS_SECRET_ACCESS_KEY >AWS_SECRET_ACCESS_KEY_ORIGINAL
echo $AWS_SESSION_TOKEN >AWS_SESSION_TOKEN_ORIGINAL
#roleArn belongs to account B whose configuration will be given below
aws sts assume-role --role-arn ${roleArn} --role-session-name devSession --region eu-west-1 >output.txt
export AWS_ACCESS_KEY_ID=$(cat output.txt | jq -r '.Credentials.AccessKeyId')
export AWS_SECRET_ACCESS_KEY=$(cat output.txt | jq -r '.Credentials.SecretAccessKey')
export AWS_SESSION_TOKEN=$(cat output.txt | jq -r '.Credentials.SessionToken')
aws sts get-caller-identity
aws eks update-kubeconfig --name eks_cluster_in_account_b
printf "\n..........................................................\n"
}

function set_account_a_creds() {
printf "\nswitching back to account a now\n"
export AWS_ACCESS_KEY_ID=$(cat AWS_ACCESS_KEY_ID_ORIGINAL)
export AWS_SECRET_ACCESS_KEY=$(cat AWS_SECRET_ACCESS_KEY_ORIGINAL)
export AWS_SESSION_TOKEN=$(cat AWS_SESSION_TOKEN_ORIGINAL)
aws sts get-caller-identity
aws eks update-kubeconfig --name eks_cluster_in_account_a
printf "\n..........................................................\n"
}

printf "\nRight now in account a\n"

export ACCOUNT_ID_NOW=$(aws sts get-caller-identity | awk -F'"' '/Account/ {print $4}')
#example value of acc-id-of-b is 229030836016. just substitue
if [[ "${ACCOUNT_ID_NOW}" != "<<acc-id-of-b>>" ]]; then
set_account_b_creds
fi
printf "\nStarting activities in Account B\n"

export ACCOUNT_ID_NOW=$(aws sts get-caller-identity | awk -F'"' '/Account/ {print $4}')
if [[ "${ACCOUNT_ID_NOW}" == "<<acc-id-of-b>>" ]]; then
set_account_a_creds
fi
printf "\nStarting activities in Account A again\n"

Trust in Account B on the role ${roleArn} looks like this:

{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Principal": {
"AWS": [
"arn:aws:iam::<<account-a-id>>:user/gitlab-ci",
]
},
"Action": "sts:AssumeRole",
"Condition": {}
}
]
}

--

--