Assuming AWS Roles for cross account CI/CD Builds

01/02/2019

When deploying code across AWS environments you should really use cross account permissions. One way to do this is to setup Roles in each of the accounts you want to deploy to. This allows your deployment service account to temporarily assume this role and have the proper permissions to do what it needs to deploy your code/infrastructure.

For example, I use the script below along with the aws cli to deploy code to my dev and prod environments. Depending on the environment I simply swap out the AWS_ROLE_ARN during my Gitlab CI jobs. AWS_ROLE_ARN look something like this: arn:aws:iam::account-id:role/role-name

#!/bin/bash
set -e
role_arn=$AWS_ROLE_ARN
session_name="${CI_BUILD_ID}-`date +%Y%m%d`"

echo 'Assuming role...'
sts=( $(
    aws sts assume-role \
    --role-arn "$role_arn" \
    --role-session-name "$session_name" \
    --query 'Credentials.[AccessKeyId,SecretAccessKey,SessionToken]' \
    --output text
) )
export AWS_ACCESS_KEY_ID=${sts[0]}
export AWS_SECRET_ACCESS_KEY=${sts[1]}
export AWS_SESSION_TOKEN=${sts[2]}

AWS Docs