Nikolas Knickrehm

1 min read

Assume AWS Role

Infrastructure as Code

We are using a custom IAM role for CloudFormation deployments that only whitelists required CRUD permissions for our stack. Every time we add new resources our deployment role can break because of insufficient permissions. This problem is often first noticed when our CI pipeline is failing.

Assume AWS Role

Luckily the AWS SDK allows assuming an IAM role while executing commands via the CLI and SDK. This is something that you should include in your development setup so that you are using the same deployment role as the CI pipeline later. A setup like this is very easy to create:

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. You must add a new profile at the end of this file that links your regular profile (e.g. "default") to the role session name of the previous step in a new additional profile.

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, you can tell the AWS CLI and SDK to use the new profile before you are doing a deployment. The easiest way to do this is to set the environment variable AWS_PROFILE to the name of the deployment role. You can do that temporarily within a terminal session, add it to a run configuration in your preferred IDE or even set it globally through your .bashrc or .zshrc:

export AWS_PROFILE=deployment

This is all you need to set up the deployment role on your development machine to always deploy with the same permissions as the CI pipeline.

Next up

Want to stay up to date?