How to add an IAM role to an existing instance in AWS?

Viewed 14932

I would like to add an IAM Role to an existing EC2 instance in AWS. I tried using AWS CLI. However, I could not find a way to do that.

5 Answers

if you are getting "The association is not the active association" error when trying to attach a role to a existing EC2 instance then you should:

1. detach the existing role from the existing EC2 instance.
2. attach a new role to the existing EC2 instance.

once you do that, you will be able to attach a role to an existing EC2 instance.

This feature was added Feb 9 2017. Note: the thing you are looking for is called an "Instance Profile". The policy describes the rights. That policy then gets added to a role and/or instance profile. I don't see any notes about specifically how to do it so I'll add as an answer.

Source document here

Specific instructions are below to conform with StackOverflow guidelines regarding link rot.

1) Create role

aws iam create-role --role-name YourNewRole --assume-role-policy-document file://YourNewRole-Trust-Policy.json

2) Attach policy to role

aws iam attach-role-policy --role-name YourNewRole --policy-arn arn:aws:iam::aws:policy/AmazonS3ReadOnlyAccess

3) Create instance profile (this is what a role is called when attached to an instance)

aws iam create-instance-profile --instance-profile-name YourNewRole-Instance-Profile

4) Add role to instance profile

 aws iam add-role-to-instance-profile --role-name YourNewRole --instance-profile-name YourNewRole-Instance-Profile

5) Attach instance profile to ec2 instance

aws ec2 associate-iam-instance-profile --instance-id YourInstanceId --iam-instance-profile Name=YourNewRole-Instance-Profile
Related