Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Allow AWS IAM user to launch only one ec2 instance

In Amazon AWS, I would like to give my IAM-registered (Windows) user a small API-based program that will launch a custom AMI-based instance and then connect her machine to it. Easy - but if the same user should try to launch another instance while the first is still running (from the same or another machine), the second and subsequent attempts must fail. The AMI will be shared between multiple users. The instance will be unique to the user.

Note that this problem differs from some similar questions because I need to launch the instance on demand, but allow no further instances. The goal is to prevent an application from being used more than is licensed.

Ideally detecting and preventing this would all happen on the AWS side, because it is more secure.

On the client side, I can see how I could use tags to do this - tag the launched instance with the users name, and search for tags before allowing an instance to start.

Is there a way to do it on the server side, with IAM policy conditions or something?

like image 601
user2793921 Avatar asked Mar 20 '23 08:03

user2793921


1 Answers

Sure. Here's a simple example, where I've given the user access to all ec2 actions except for those I've explicitly denied if a ResourceTag with the key "MyTag" and value "MyTagValue" exist.

Denied actions:

  • PurchaseReservedInstancesOffering
  • RequestSpotInstances
  • RunInstances

Example:

{
  "Statement": [
    {
      "Action": [
        "ec2:PurchaseReservedInstancesOffering",
        "ec2:RequestSpotInstances",
        "ec2:RunInstances"
      ],
      "Effect": "Deny",
      "Resource": "*",
      "Condition": {
        "StringLike": {
          "ec2:ResourceTag/MyTag": "MyTagValue"
        }
      }
    },
    {
      "Action": "ec2:*",
      "Effect": "Allow",
      "Resource": "*"
    }   
  ]
}

Here's proof of the results from the IAM Policy Simulator:

A screenshot of the IAM Policy Simulator, showing several denied actions.

Those actions are allowed when that tag doesn't exist, is some other value, etc.

Also, the ec2 allow action "Action": "ec2:*" was for sake of example... you can remove that whole block or use it as a template to begin allowing only a specific set of EC2 actions to your users.

like image 138
Anthony Neace Avatar answered Apr 01 '23 08:04

Anthony Neace