How do I create an IAM policy to control access to Amazon EC2 resources using tags?

Last updated: 2019-04-17

How do I create an AWS Identity and Access Management (IAM) policy that controls access to Amazon Elastic Compute Cloud (Amazon EC2) instances using tags?

Short Description

You can control access to smaller deployments of Amazon EC2 instances as follows:

  1. Add a specific tag to the instances you want to grant the users or groups access to.
  2. Create an IAM policy that grants access to any instances with the specific tag.
  3. Attach the IAM policy to the users or groups that you want to access the instances.

Resolution

Add a tag to your group of EC2 instances

Open the Amazon EC2 console, and then add tags to the group of EC2 instances that you want the users or groups to be able to access. If you don't have a tag already, create a new tag.

Note: Be sure to read and understand the Tag Restrictions before tagging your resources. Amazon EC2 tags are case-sensitive.

Create an IAM policy that grants access to instances with the specific tag

Create an IAM policy that does the following:

  • Allows control over the instances with the tag.
  • Contains a conditional statement that allows access to Amazon EC2 resources if the value of the condition key ec2:ResourceTag/UserName matches the policy variable aws:username. The policy variable ${aws:username} is replaced with the friendly name of the current IAM user when the policy is evaluated by IAM.
  • Allows access to the ec2:Describe* actions for Amazon EC2 resources.
  • Explicitly denies access to the ec2:CreateTags and ec2:DeleteTags actions to prevent users from creating or deleting tags.
    Note: This prevents the user from taking control of an EC2 instance by adding the specific tag to it.

For example, the finished policy should look similar to the following:

{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Effect": "Allow",
      "Action": "ec2:*",
      "Resource": "*",
      "Condition": {
        "StringEquals": {
          "ec2:ResourceTag/UserName": "${aws:username}"
        }
      }
    },
    {
      "Effect": "Allow",
      "Action": "ec2:Describe*",
      "Resource": "*"
    },
    {
      "Effect": "Deny",
      "Action": [
        "ec2:CreateTags",
        "ec2:DeleteTags"
      ],
      "Resource": "*"
    }
  ]
}

Attach the IAM policy to the users or groups you want to access the instances

Finally, attach the IAM policy that you created to the users or groups you want to access the instances. You can attach the IAM policy using the AWS Management Console, AWS CLI, or AWS API.