Monday, March 14, 2022

[SOLVED] AWS: Limit which IAM roles can be attached to an EC2 instance by different IAM users

Issue

Im trying to figure out if this is possible. I have 2 IAM users. I would like each one to be able to start/stop the same EC2 instance but have each IAM user be able to attach a different IAM role to this one EC2 instance. In other words, user1 should only be able to attach role1 to this ec2 instance, while user2 should only be able to attach role2 to this same EC2 instance. They would be using the ec2 instance at different times.

I'm using the aws ec2 associate-iam-instance-profile command to attach the IAM profile to the EC2 instance before starting it up and then detaching the profile once I shut it down. I would like for each IAM user to be able to attach only a specific IAM role to this one EC2 instance.

Is this possible? Any ideas or examples? Thank you!


Solution

The following IAM policy for both users should be enough:

{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Sid": "VisualEditor0",
            "Effect": "Allow",
            "Action": "ec2:AssociateIamInstanceProfile",
            "Resource": "<arn-of-the-instance>"
        },
        {
            "Sid": "VisualEditor1",
            "Effect": "Allow",
            "Action": "iam:PassRole",
            "Resource": "arn:aws:iam::xxxx:role/<role-name>"
        }
    ]
}

The above allows to only pass one specific role and AssociateIamInstanceProfile to one one specific instance.

However, this does not include detaching of the profiles from instances.



Answered By - Marcin
Answer Checked By - Candace Johnson (WPSolving Volunteer)