Assume AWS Role

Assume AWS Role

We are using a custom IAM role for CloudFormation deployments, that only whitelists required CRUD permissions for our stack. Everytime we add new resources, the deployment role can break, because of insufficient permissions. This problem is often only unnoticed, when our CI pipeline fails.

Luckily the AWS SDK allows to assume an IAM role, while executing tasks through the CLI or SDK. This is something, that I highly recommend to automate in your development setup, so that you will notice problems with the deployment role very early on and not just in your CI pipeline. This setup is actually quite easy to achieve with just a few steps:

First, you need to use the AWS CLI to assume the role and create a session for it on your computer. Remember the session name (e.g. "deployment") as you will need it in the next step.

aws sts assume-role --role-arn <role arn> --role-session-name deployment

Next, you can modify your AWS credentials file located in ./aws/credentials and add a new profile at the end, that is based on your regular profile (e.g. "default") and assumes the role with the session name, that you have specified in the previous step.

role_arn          = # The ARN of the role, that you want to assume
source_profile    = # A custom profile or default
role_session_name = # The role session name specified in the previous step

Now, every time you want to use the deployment role, you just need to make sure to specify this new profile. The easiest way to do that, is to set the environment variable AWS_PROFILE to the name of this profile. You could do that on demand for a single terminal session or even permanently in your .bashrc or .zshrc:

export AWS_PROFILE=deployment

This is all you need to setup the deployment role on your development machine.

Share this article

Subscribe for more

Check your inbox and click the link to confirm your subscription.
Please enter a valid email address!