Creating IAM User policy for EC2

Creating IAM User policy for EC2

ยท

2 min read

Let's talk about policies, Policies are sets of permissions that define what actions users or entities are allowed or denied within AWS services. AWS policies are typically written in JSON (JavaScript Object Notation) format and are attached to AWS Identity and Access Management (IAM) entities, such as users, groups, or roles.

AWS policies are used to control access to AWS resources and services.

In this tutorial, let's take an example of creating a customer-managed policy that only allows the creation of "t2" family EC2 instance types in the N. Virginia region. This means the user can only create EC2 instances with types that start with "t2" in the N. Virginia region.

We can use the AWS Policy Generator for this. It makes it easier for us to create policies in JSON format.

Now, let's break down the conditions here. The first condition will be to allow usage in the 't2family' instance type, and the second condition will be to create resources in the N. Virginia region.

First, we need to specify the "ALLOW" effect:

For simplicity, click on "All Actions".

The ARN should be "arn:aws:ec2:::instance/*", which means allowing access to all regions, accounts, and resource paths.

Subsequently, click on "Add Condition" modify the condition as follows and add the statement:

Moving forward for the 'DENY' effect:

In the actions section, under the denying effect, select "RUN INSTANCES". Once again, add the condition mentioned above, and fill in the gaps as shown below:

Click on "Generate Policy". The policy generator tool will then provide us with the policy in JSON format, which is as follows:

{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Sid": "Stmt1688455513192",
      "Action": "ec2:*",
      "Effect": "Allow",
      "Resource": "arn:aws:ec2:*:*:instance/*",
      "Condition": {
        "StringEquals": {
          "aws:RequestedRegion": "us-east-1"
        }
      }
    },
    {
      "Sid": "Stmt1688456301119",
      "Action": [
        "ec2:RunInstances"
      ],
      "Effect": "Deny",
      "Resource": "arn:aws:ec2:*:*:instance/*",
      "Condition": {
        "StringNotLike": {
          "ec2:InstanceType": "t2.*"
        }
      }
    }
  ]
}

Please take note of the following point: The request first goes to the 'deny' effect before proceeding to the 'allow' effect.

The final step is to Attach the inline policy to the required user group.

ย