AWS IAM: Allow EC2 instance to stop itself

对着背影说爱祢 提交于 2019-12-10 10:34:17

问题


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?


回答1:


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



回答2:


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



来源:https://stackoverflow.com/questions/39018803/aws-iam-allow-ec2-instance-to-stop-itself

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!