How can I restrict access to a specific IAM role session using an IAM identity-based policy?

Last updated: 2022-01-31

I want to grant permissions to a specific AWS Identity and Access Management (IAM) role session with an identity-based policy.

Resolution

Create an IAM policy to allow access to a specific IAM role session using the AWS global condition context key aws:userid.

Note: If you receive errors when running AWS Command Line Interface (AWS CLI) commands, make sure that you’re using the most recent AWS CLI version.

The aws:userid global condition key checks if the Unique ID of the principal making the request matches the Unique ID specified in the IAM policy.

For example, if you want to allow a specific IAM role session to perform only specific Amazon Elastic Compute Cloud (Amazon EC2) actions in your AWS account. Create an IAM policy similar to the following:

{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Sid": "AllowASpecificRoleSession",
            "Effect": "Allow",
            "Action": [
                "ec2:StartInstances",
                "ec2:StopInstances",
                "ec2:RebootInstances",
                "ec2:TerminateInstances"
            ],
            "Resource": "*",
            "Condition": {
                "StringEquals": {
                    "aws:userid": "AROAXXXXXXXXXXXXXXXXX:<role-session-name>"
                }
            }
        }
    ]
}

This IAM policy grants the Amazon EC2 instance access to the IAM role session in the aws:userid global condition key. Other role sessions can't perform any Amazon EC2 actions.

To get the role ID for the IAM role, run the following AWS CLI command:

$ aws iam get-role --role-name <rolename>

You receive an output similar to the following:

{
    "Role": {
        "Description": "Test Role",
        "AssumeRolePolicyDocument":"<URL-encoded-JSON>",
        "MaxSessionDuration": 3600,
        "RoleId": "AROA1234567890EXAMPLE",
        "CreateDate": "2019-11-13T16:45:56Z",
        "RoleName": "Test-Role",
        "Path": "/",
        "RoleLastUsed": {
            "Region": "us-east-1",
            "LastUsedDate": "2019-11-13T17:14:00Z"
        },
        "Arn": "arn:aws:iam::123456789012:role/Test-Role"
    }
}

In the output, check for the RoleId string. The role ID is used in the identity-based policy to scope Amazon EC2 instances access to the IAM role session.

Note: The aws:userid global condition key can be used in any type of IAM policy such as an identity-based policy, resource-based policy, permission boundary policy, and so on. The values for aws:userid global condition key depend on what type of principal initiates the request. To determine the values for different types of principals, see Information available in all requests.