user1834095
user1834095

Reputation: 5723

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?

Upvotes: 8

Views: 2694

Answers (3)

Oleksandr S.
Oleksandr S.

Reputation: 2034

You can use aws:userid and ec2:InstanceID in the condition element:

{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Effect": "Allow",
            "Action": ["ec2:StopInstances"],
            "Resource": ["arn:aws:ec2:*:*:instance/*"],
            "Condition": {
                "StringLike": {
                    "aws:userid": "*:${ec2:InstanceID}"
                }
            }
        }
    ]
}

Upvotes: 2

Tomasz Kapłoński
Tomasz Kapłoński

Reputation: 1378

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

Upvotes: 7

user1834095
user1834095

Reputation: 5723

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).

Upvotes: 0

Related Questions