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

2 minute read
0

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

Resolution

To create an IAM policy that allows access to a specific IAM role session, use the AWS global condition context key aws:userid.

Note: If you receive errors when you run AWS Command Line Interface (AWS CLI) commands, then see Troubleshoot AWS CLI errors. Also, make sure that you're using the most recent AWS CLI version.

The aws:userid global condition key checks whether the unique ID of the principal that's making the request matches the unique ID specified in the IAM policy. For example, to allow an IAM role session to perform specific Amazon Elastic Compute Cloud (Amazon EC2) actions in your AWS account, create an IAM policy:

{
  "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 Amazon EC2 actions.

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

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

You receive an output similar to the following:

{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Sid": "VisualEditor0",
      "Effect": "Allow",
      "Action": [
        "s3:PutObject",
        "s3:GetObject",
        "s3:ListBucket"
      ],
      "Resource": [
        "arn:aws:s3:::example-bucket/example-folder/*"
      ]
    }
  ]
}

In the output, check for the RoleId string. The role ID is used in the identity-based policy to scope the Amazon EC2 instance's 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, and permission boundary policy. 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 Principal key values.

Related information

Can I restrict the access of IAM Identity to specific Amazon EC2 resources?

How can I use IAM policy tags to restrict how an EC2 instance or EBS volume can be created?

AWS OFFICIAL
AWS OFFICIALUpdated 7 months ago