amazon-web-servicesamazon-ec2amazon-iamrole

How to update roles to all EC2s


I need to patch a o lot of EC2 using system manager. so I need to add policies such as AmazonEC2RoleForSSM and AmazonSSMFullAccess to the EC2. currently they do not have the policies in the role.

if all of the EC2 need to add these two policies, then I just need to add the policies to the role. but what if some of the EC2 need, some do not?

I think I should create a new role with these two policies and then replace some EC2s with these new role. how to do that? it seems the AWS console can only replace role of one EC2 each time.


Solution

  • Once you create a new role, use AWS SDK or AWS CLI to attach the role to EC2 instances. Get a list of instance-ids that you want the role attached to. Write a simple script to loop through the list and call AWS CLI for each instance-id. Similarly in a SDK, you can loop through the list and call the API for each instance-id.

    AWS CLI: associate-iam-instance-profile or replace-iam-instance-profile-association

    AWS SDK: Depending on the language you can program in, there are API(s) to attach or replace instance IAM profile. AWS SDK