Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AWS IAM: Allow EC2 instance to stop itself

I'm trying to allow all EC2 instances in our AWS account to stop themselves (using an automated script that uses the aws cli). I try to do so by creating an AWS IAM role with the propper policy. However, I can't find how to define the policy to only Allow instances to stop itself (and not other instances).

I tried with the following policy

{
     "Version": "2012-10-17",
     "Statement": [
         {
             "Effect": "Allow",
             "Action": [
                 "ec2:StopInstances"
             ],
             "Resource": [
                 "${ec2:SourceInstanceARN}"
             ]
         }
     ]
}

But on validation, this gives me the error This policy contains the following error: The following resources are invalid : ${ec2:SourceInstanceARN}

Is there a way to allow an instance to stop itself (and only itself)? If so, how should I do it?

like image 645
user1834095 Avatar asked Aug 18 '16 12:08

user1834095


1 Answers

Shutdown behavior solves the problem with termination but there might be other scenarios that require limited access to API requests (i.e. self tagging). So here's a solution with IAM policy:

{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Sid": "VisualEditor0",
            "Effect": "Allow",
            "Action": [
                "ec2:DeleteTags",
                "ec2:DescribeTags",
                "ec2:CreateTags",
                "ec2:TerminateInstances",
                "ec2:StopInstances"
            ],
            "Resource": "*",
            "Condition": {
                "StringEquals": {
                    "aws:ARN": "${ec2:SourceInstanceARN}"
                }
            }
        }
    ]
}
like image 119
Tomasz Kapłoński Avatar answered Sep 28 '22 12:09

Tomasz Kapłoński