5
votes

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?

2
Any reason you can't just use the OS's shutdown command in your script, instead of using the AWS CLI?Mark B
Ah, of course, how could I forget! Please post this as an answer, then I'll accept it. For me, this would definitely work. However, I can think of two reasons why other people wouldn't want to use shutdown. 1. shutdown can only be executed with root permission so you need sudo right to be able to do so. 2. If the shutdown behavior of the instance would be terminate, you'll lose the instance rather than stopping it.user1834095

2 Answers

6
votes

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}"
                }
            }
        }
    ]
}
0
votes

As Mark B suggested in the comments, I solved my problem by changing my script to use shutdown rather than aws ec2 stop-instances. This makes the use of any policy needless, as any system can execute shutdown on itself (and only itself).