How to assume an IAM role in AWS – Simplest method


In the world of AWS, IAM roles are a fundamental concept that you have to get right for your applications to function optimally.

Roles give your AWS services the necessary permissions to access resources they need. But you can also assume roles via the AWS CLI in order to access AWS resources instantly from the terminal or AWS Console.

From day to day basis I have to access dozens of different AWS accounts and therefore it’s impossible to maintain IAM users and instead use IAM roles and AWS SSO to easily authenticate myself and get access to restricted resources.

Using the native AWS CLI command like aws sts assume-role is hard remember and painful to write out for multiple roles.

Therefore I’ve written this blog post to introduce an open-source tool that I use on a daily basis to significantly improve my productivity by making assuming roles as simple and easy as it can.

In short, you can use the open-source tool “Granted” from Common-fate to assume the role and export the AWS credentials in your terminal with a single command:

assume <aws-profile-name> 

Down below, we will dive deeper in one of the easiest methods to assume an IAM role and show you how you can open AWS STS sessions in the AWS CLI and AWS Console.

What is an IAM Role?

In AWS an IAM role is a set of permissions that define what actions are allowed and denied by an entity (user or service) in AWS.

Unlike IAM users, IAM roles do not have long-term credentials associated with them. Instead, they provide temporary security credentials that allow you to delegate access to various AWS services.

An IAM role is not associated with a specific user or group but is intended to be assumable by trusted entities. This makes IAM roles highly flexible and secure, as they can be assumed by AWS services like EC2 or Lambda, or by users in your own or another AWS account.

Here’s a breakdown of what an IAM role is:

  • Permissions: Defines what actions are allowed or denied.
  • Trust Policy: Specifies who (which AWS accounts, IAM users, or AWS services) can assume the role.
  • Use Cases: Delegating permissions, cross-account access, temporary access, etc.

IAM roles are a powerful tool to ensure that you’re adhering to the principle of least privilege, granting only the permissions necessary to perform a task.

What is assuming a Role?

Assuming a role is a process that enables you to take on the permissions of an IAM role temporarily. When you assume a role, you receive temporary security credentials that you can use to make AWS API requests.

This is different from switching to a different IAM user, as you’re not changing your identity, just taking on additional permissions for a specific task or operation.

Here’s how “Assume Role” works:

  1. Define the Role: Create an IAM role with the necessary permissions and a trust policy that specifies who can assume the role.
  2. Assume the Role: Use AWS services like AWS STS (Security Token Service) to assume the role. You can do this programmatically or via the AWS CLI.
  3. Receive Temporary Credentials: Once the role is assumed, you receive temporary security credentials that provide the permissions of the role.
  4. Make API Requests: Use the temporary credentials to make AWS API requests.
  5. Revert to Original Permissions: Once you’re done, you revert to your original permissions, and the temporary credentials expire.

The ability to assume roles is particularly useful for cross-account access, temporary elevated permissions, and delegating permissions to AWS services. It enhances security by allowing you to grant permissions temporarily and only when needed.

Prerequisites

Before you can access the AWS CLI and AWS Console with your assumed IAM role via an IAM user or AWS SSO user, you need to have installed the following tools first:

  • AWS CLI
  • Granted CLI

1. Install the AWS CLI

The AWS CLI allows you to interact with AWS services in your terminal. Currently, there are two versions available v1 and v2, but we’re going to install the latter.

With Homebrew we install AWS CLI v2 with the following command:

brew install awscli

To install AWS CLI v2 on other operation systems, visit the AWS docs

You can validate the version by running aws --version:

aws-cli/2.2.5 Python/3.9.5 Darwin/20.4.0 source/x86_64 prompt/off

2. install the Granted CLI

The Granted CLI is an open-source tool developed by Common-Fate that makes it easier to assume IAM roles in AWS.

Let’s walk through the steps of how to install this tool on MacOS:

  1. Open your terminal.
  2. Install the Granted CLI with Homebrew by using the following command:
brew tap common-fate/granted
brew install granted
  1. Verify the installation by checking the version of Granted:
granted --version

Here are the steps to install Granted on Linux, and Windows systems.

How to assume an IAM role in AWS using the CLI

Now that the prerequisites are met, you can follow these steps to assume a role on the AWS Console and AWS CLI using a single command:

  1. Create an IAM user
  2. Create an SSO (login) user
  3. Create an IAM Role with a trust relation with the created IAM User
  4. Use Granted to STS Assume the Role in the CLI via IAM User

1. Create an IAM User

You can easily create an IAM user from the AWS Management Console using the steps below:

  1. Navigate to the IAM console on your AWS account.
  2. In the navigation pane, choose ‘Users’ and then choose ‘Add user’.
  3. Input a ‘User name’ and select ‘Programmatic access’ for the ‘Access type’.
  4. On the permissions page, you can attach an existing policy directly or create one that suits your requirements. For example, you might want to provide the user with AmazonS3FullAccess, so you can find that policy and select it.
  5. Review your choices and then click ‘Create user’.
Create IAM user in AWS Console, review step.
  1. After the user is created, the console shows the user’s access key ID and secret access key.
  2. Download the credentials and copy them ~/.aws/credentials location like so:
[my-user]
aws_access_key_id = YOUR_ACCESS_KEY
aws_secret_access_key = YOUR_SECRET_KEY

2. Create an AWS SSO (login) user

Assuming a role via AWS IAM Identity Center (formerly known as AWS SSO) is the best way to manage your AWS user authentication for all your AWS Accounts.

Before you can create your AWS SSO user and store the AWS profile locally on your machine you first need to enable AWS IAM Identity center.

An in-depth guide on how to set it up can be found on my other blog post, in the link below 👇

3. Create an IAM Role with a trust relation with the created IAM User

Next, we will create an IAM role that the IAM or SSO user can assume.

  1. In the IAM console, in the navigation pane, choose ‘Roles’ and then choose ‘Create role’.
  2. Choose ‘Custom trust policy’.
  3. In the policy document, you’ll need to specify the ‘Principal’ that will be allowed to assume this role. You can specify your AWS account id to allow your IAM user or SSO user to assume the role. Here’s a sample policy:
{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Effect": "Allow",
      "Principal": {
        "AWS": "arn:aws:iam::YOUR_ACCOUNT_ID:root"
      },
      "Action": "sts:AssumeRole"
    }
  ]
}
  1. Then choose ‘Next: Permissions’.
  2. For the permissions policy, select your preferred permission by selecting a pre-defined policy.
  3. Choose ‘Next: Tags’.
  4. Choose ‘Next: Review’.
Create IAM role in the AWS Console with trust relationship policy. Review section.
  1. For ‘Role name’, enter a name for your role. Choose ‘Create role’.
  2. Next, create the ~/.aws/config profile for the IAM role. This profile allows your user to assume the role. The format of the profile should be as follows:
[profile my-role]
role_arn = arn:aws:iam::YOUR_ACCOUNT_ID:role/YOUR_IAM_ROLE
source_profile = my-user  # The IAM or SSO profile you created in the previous step

4. Use Granted to assume the role in the CLI via IAM or SSO User

Finally, you can use Granted to assume the role in the CLI.

Run the command assume my-role to assume the role via the IAM user you’ve just created:

➜ assume my-role
[✔] [my-role](us-east-1) session credentials will expire in 1 hour

If you wish to verify that you’ve assumed the right role then you can use the aws sts get-caller-identity command to get your AWS Session details:

~ on  my-role (us-east-1) [32m50s]
✗ aws sts get-caller-identity
{
    "UserId": "AROAUNK7YPUGD5AUMRR6S:dannysteenman",
    "Account": "0123456789012",
    "Arn": "arn:aws:sts::0123456789012:assumed-role/AWSReservedSSO_AdministratorAccess_a9c7ffeeffd4bea4/dannysteenman"
}

5. Use Granted to assume the role and open the AWS Console

What makes this tool special is that it not only assumes roles for your AWS CLI but it can also open a session in the AWS Console browser.

To do that you need to append the argument –console to the assume command like so:

➜ assume my-role --console
[i] use -s to open a specific service ( https://docs.commonfate.io/granted/usage/console )
[i] Opening a console for my-role in your browser...

It will open the AWS Console automatically in your default browser.

How to assume an IAM role and export its credentials in your terminal

A big benefit to using the granted CLI is that it will automatically export the values of AccessKeyIdSecretAccessKey and SessionToken when you assume an IAM role with the command: assume <aws-profile-name>.

To show you how you can check that in your terminal, use the command env | grep AWS after assuming the IAM role:

~/github on  my-role (us-east-1) [36m16s]
➜ env|grep AWS
AWS_ACCESS_KEY_ID=ASIAQE7WYRKTKQ55ZTU2
AWS_SECRET_ACCESS_KEY=mu9LfNc3t9VuaB15MdTALPCbQrxAmxMPT+Evpp6g
AWS_SESSION_TOKEN=IQoJb3JpZ2luX2VjEID//////////wEaDGV1LWNlbnRyYWwtMSJHMEUCIQCMU0n8yaLZfKMC5F0FvZDfIsK0VmjQSvQ6PNeaZbjqSgIgWwTBLq5qb3fxtREkkGz42frTj/je5DIy2B3N7idEX00qrQIIKRAAGgwwMTA3MTM5OTU5MzciDCthegqx+mfPzN/koiqKAjUJa4H5iwUgfHeVDbOGxKFuqtW4Ns1n/V5a7tESqcdAOOaRF/zTm6VYwJGYBxeEjbM3d08ueuv+L6pIv16ZkHzz3WafdulnIKAWEO9sgm9N1XynEi4WiApQ5n9scaTwWJO0x1W6DosmFiYNYrwl4EPWtDRs+AlFmiclML3ksqYGOp0BHPL5EY4LxCGL5H++svj6UaBsQVaaB1bIjAYjYLbPufZIVQ0PLldpvPGENsRKFsoX0MN7Iew8N42jGwU5YWvEIF77jtSUQUzQ/OhJDB8JTxP+46/UJgyrcU/8KzIWadkHsgjOyDEg2MKSg0ToGAfkk4VD4US/yv0c/wI630E23DGtDmqt+4Xo55qaC4rODhNFql6MkNI0joCN66bbulIysbvxFIV/8wOhkWReTuUKg5rs2fSfVRiZNh/90YtLMhmmvLgb/GjeWua5fJ8aPqU6IcgGrWaDx0iSji4PJ132uvlJHWjgOCurr5kJuOkL+AtjT9LQNNhiKIkiDPBNzs4Dzc3cOCUI0YDsACVbXBGr/FIrUTlR/Fs7aymwI2O4Zv1AqYaGm1w2XhP6Aqx2Sg==
AWS_PROFILE=my-role
AWS_REGION=us-east-1
AWS_SESSION_EXPIRATION=2023-08-04T11:09:33+02:00
AWS_CREDENTIAL_EXPIRATION=2023-08-04T11:09:33+02:00

As an added bonus it will also automatically export AWS_PROFILE, AWS_REGION, AWS_SESSION_EXPIRATION and AWS_CREDENTIAL_EXPIRATION in your terminal session.

These environment variables are useful for development tools such as AWS CDK, AWS SAM and Terraform. Because it allows you to deploy from the session you assumed in your terminal.

Conclusion

Assuming an IAM role in AWS may initially seem complex, but with tools like Granted and a step-by-step guide, you can easily secure your AWS resources and streamline your cloud operations.

Remember, the trust relationship policy is pivotal to the whole process. And most importantly, always remember to follow the principle of least privilege when assigning permissions to your IAM roles.

Now, you’re ready to assume roles and conquer the AWS Cloud world.



Danny Steenman

A Senior AWS Cloud Engineer with over 9 years of experience migrating workloads from on-premises to AWS Cloud.

I have helped companies of all sizes shape their cloud adoption strategies, optimizing operational efficiency, reducing costs, and improving organizational agility.

Connect with me today to discuss your cloud aspirations, and let’s work together to transform your business by leveraging the power of AWS Cloud.

I need help with..
stacked cubes
Improving or managing my CDK App.Maximize the potential of your AWS CDK app by leveraging the expertise of a seasoned CDK professional.
Reducing AWS Costs.We can start by doing a thorough assessment of your current AWS infrastructure, identifying areas with potential for cost reduction and efficiency improvement.
Verifying if my infrastructure is reliable and efficient.We’ve created a comprehensive AWS Operations Checklist that you can utilize to quickly verify if your AWS Resources are set up reliably and efficiently.