I want to assume an Amazon Identity and Access Management (IAM) role using the AWS Command Line Interface (CLI). How can I do this?

You can follow these instructions to assume an IAM role using AWS CLI.

Note: You must have an IAM user that has permissions to assume roles; follow these instructions to create one if you haven't already done so.

In this example, the user will have read-only access to EC2 instances and permission to assume an IAM role.

Create an IAM user named test-user using AWS CLI:

aws iam create-user --user-name test-user

Create the IAM policy that will grant the permissions to test-user using AWS CLI. You must create the JSON file that defines the IAM policy using your favorite text editor. This example uses vim, which is commonly used in Linux:

vim test-policy.json

The contents of the test-policy.json file should be similar to this command:

{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Effect": "Allow",
            "Action": [
                "ec2:Describe*",
                "iam:ListRoles",
                "sts:AssumeRole"
            ],
            "Resource": "*"
        }
    ]
}

For more information about creating IAM policies, see Creating a New Policy, Example Policies, and AWS IAM Policy Reference.

Create the IAM managed policy with this AWS CLI command:

aws iam create-policy --policy-name test-policy --policy-document file://test-policy.json

This command outputs several pieces of information, including the ARN (Amazon Resource Name) of the IAM policy:

arn:aws:iam::123456789012:policy/test-policy

Take note of the IAM policy ARN from the output, and attach the policy to test-user using CLI command of 'attach-user-policy'. Check to ensure that the attachment is in place using 'list-attached-user-policies':

aws iam attach-user-policy --user-name test-user --policy-arn "arn:aws:iam::123456789012:policy/test-policy"
aws iam list-attached-user-policies --user-name test-user

Note: Replace 123456789012 with your own account ID.

Create an IAM role that can be assumed by test-user that has read-only access to RDS DB instances. Create the JSON file that defines the trust relationship of the IAM role. Because this IAM role is assumed by an IAM user, you must specify a principal that allows IAM users to assume that role. For example, a principal similar to arn:aws:iam::123456789012:root will allow all IAM identities of the account to assume that role. For more information, see Creating a Role to Delegate Permissions to an IAM User.

You can also restrict the trust relationship so that the IAM role can only be assumed by specific IAM users. This can be accomplished by specifying principals similar to arn:aws:iam::123456789012:user/<username>. For more information, see Individual IAM user or users.

Create the JSON file that defines the trust relationship:

vim test-role-trust-policy.json

The contents of the test-role-trust-policy.json file should be similar to this:

{
    "Version": "2012-10-17",
    "Statement": {
        "Effect": "Allow",
        "Principal": { "AWS": "arn:aws:iam::123456789012:root" },
        "Action": "sts:AssumeRole"
    }
}

Create the IAM role that has read-only access to RDS DB instances. Attach the IAM policies to your IAM role according to your security requirements.

The first AWS CLI command creates the IAM role and defines the trust relationship according to the contents of the JSON file. The second command attaches the AWS Managed Policy AmazonRDSReadOnlyAccess to the role. You can attach different policies (Managed Policies and Custom Policies) according to your security requirements. The third command shows the IAM policies that are attached to the IAM role test-role.

aws iam create-role --role-name test-role --assume-role-policy-document file://test-role-trust-policy.json
aws iam attach-role-policy --role-name test-role --policy-arn "arn:aws:iam::aws:policy/AmazonRDSReadOnlyAccess"
aws iam list-attached-role-policies --role-name test-role

Check test-user to verify that it has read-only access to EC2 instances, and if it's able to assume the test-role. Create access keys for test-user with this command:

aws iam create-access-key --user-name test-user

The AWS CLI command will output an access key ID and a secret access key; take note of these keys.

To configure the access keys, use either the default profile or a specific profile. To configure the default profile, run aws configure. To create a new specific profile, run aws configure --profile <profile-name> replacing <profile-name> with a name of your choice. In this example, the default profile is configured:

aws configure
AWS Access Key ID [None]: <Access-Key-provided-by-create-access-key>
AWS Secret Access Key [None]: <Secret-Access-Key-provided-by-create-access-key>
Default region name [None]: eu-west-1
Default output format [None]: json

Note: For region name, specify your AWS region.

Verify that your AWS CLI commands are being invoked as test-user by running this command:

aws sts get-caller-identity

This command will output three pieces of information including ARN. It should show something similar to arn:aws:iam::123456789012:user/test-user, which verifies that the AWS CLI commands are invoked as test-user.

Confirm that the IAM user has read-only access to EC2 instances and no access to RDS DB instances by running these commands:

aws ec2 describe-instances --query "Reservations[*].Instances[*].[VpcId, InstanceId, ImageId, InstanceType]"
aws rds describe-db-instances --query "DBInstances[*].[DBInstanceIdentifier, DBName, DBInstanceStatus, AvailabilityZone, DBInstanceClass]"

The first AWS CLI command should show you all the EC2 instances that are in the eu-west-1 region. The second AWS CLI command must generate an access denied error message because test-user doesn't have access to RDS.

To assume the test-role, you must get the ARN of the role by running this command:

aws iam list-roles --query "Roles[?RoleName == 'test-role'].[RoleName, Arn]"

The command lists IAM roles but filters the output by role name. To assume the IAM role, run this command:

aws sts assume-role --role-arn "arn:aws:iam::123456789012:role/test-role" --role-session-name AWSCLI-Session

The AWS CLI command outputs several pieces of information. Inside the credentials block you will need: AccessKeyId, SecretAccessKey, and SessionToken. Take note of the timestamp of the expiration field. It is in the UTC timezone and indicates when the temporary credentials of the IAM role will expire. If this happens, you must invoke the sts:AssumeRole API call again.

After you have run aws sts assume-role, you can create three environment variables to assume the IAM role. These environment variables are filled out with this output:

export AWS_ACCESS_KEY_ID=<AccessKeyId>
export AWS_SECRET_ACCESS_KEY=<SecretAccessKey>
export AWS_SESSION_TOKEN=<SessionToken>

Verify that you have assumed the IAM role by running this command:

aws sts get-caller-identity

The AWS CLI command should output the ARN as arn:aws:sts::123456789012:assumed-role/test-role/AWSCLI-Session instead of arn:aws:iam::123456789012:user/test-user, which verifies that you have assumed the test-role.

You have created an IAM role with read-only access to RDS DB instances, but no access to EC2 instances. Verify by running these commands:

aws ec2 describe-instances --query "Reservations[*].Instances[*].[VpcId, InstanceId, ImageId, InstanceType]"
aws rds describe-db-instances --query "DBInstances[*].[DBInstanceIdentifier, DBName, DBInstanceStatus, AvailabilityZone, DBInstanceClass]"

The first command should generate an access denied error message, and the second should return the RDS DB instances. This verifies that the permissions assigned to the IAM role are working correctly.

To return to the IAM user, remove the environment variables:

unset AWS_ACCESS_KEY_ID AWS_SECRET_ACCESS_KEY AWS_SESSION_TOKEN
aws sts get-caller-identity

The first command removes the environment variables, and the second command verifies that you have returned as test-user.

You can also use a role by creating a profile in the ~/.aws/config file. For more information, see Assuming a Role.


Did this page help you? Yes | No

Back to the AWS Support Knowledge Center

Need help? Visit the AWS Support Center

Published: 2017-09-06