jbbb
jbbb

Reputation: 65

AWS IAM Roles: Policy with permissions only over the instance itself and not every resource

I'll try to explain my issue the best I can.

I want to create an IAM Role with my own RebootPolicy that, when attached to an EC2 instance, allows that instance to reboot itself (but only itself). Currently the only thing I can do is create a role with a policy that allows Reboot in all instances.

{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Sid": "VisualEditor0",
            "Effect": "Allow",
            "Action": "ec2:RebootInstances",
            "Resource": "*"
        }
    ]
}

I know I could technically add the specific id of the instance to the policy, but the idea is that I use the policy in any instance I want and not just an specific one. I tried following the documentation at https://docs.aws.amazon.com/IAM/latest/UserGuide/list_amazonec2.html but I don't know how to implement it.

Any ideas? Thanks in advance!

Upvotes: 5

Views: 2249

Answers (2)

John Rotenstein
John Rotenstein

Reputation: 270124

I think you can use: $(aws:userid)

IAM Policy Elements: Variables and Tags says:

aws:userid will be set to role-id:ec2-instance-id where role-id is the unique id of the role and the ec2-instance-id is the unique identifier of the EC2 instance.

Upvotes: 1

jellycsc
jellycsc

Reputation: 12349

You can self reference EC2 by using ec2:SourceInstanceARN IAM policy variable.

{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Sid": "VisualEditor0",
            "Effect": "Allow",
            "Action": "ec2:RebootInstances",
            "Resource": "*",
            "Condition": {
                "StringEquals": {
                    "aws:ARN": "${ec2:SourceInstanceARN}"
                }
            }
        }
    ]
}

Upvotes: 7

Related Questions