How do I attach or replace an instance profile on an Amazon EC2 instance?

Last updated: 2019-08-07

How do I attach or replace an instance profile on an Amazon Elastic Compute Cloud (Amazon EC2) instance?

Resolution

Follow these instructions to attach or replace an instance profile on an EC2 instance.

Note: If you create the AWS Identity and Access Management (IAM) role using the AWS Command Line Interface (AWS CLI), you must also create the instance profile using the AWS CLI. The IAM role name and instance profile name can be different because multiple steps are used to create and add the role to the instance profile, and then attach that role to the EC2 instance. However, if you create the role using the AWS Management Console and choose EC2 as the AWS service that the role is used for, the instance profile and IAM role names are the same.  

AWS Management Console

  1. Open the Amazon EC2 console, and then choose Instances.
  2. Choose the instance that you want to attach an IAM role to.
  3. Check the IAM role under the Description view of the Launch Instance pane to confirm if an IAM role is attached to the Amazon EC2 instance. If an IAM role is attached, be sure that changing the role attached to this Amazon EC2 instance doesn't affect your applications or access to AWS services.
  4. Choose Actions, choose Instance Settings, and then choose Attach/Replace IAM role.
  5. On the Attach/Replace IAM role page, under IAM role, choose the instance profile that you want to attach from the drop-down list.
  6. Choose Apply.

AWS Command Line Interface (AWS CLI)

Add the role to an instance profile before attaching the instance profile to the EC2 instance.

1.    If you haven't already created an instance profile, run the following AWS CLI command:

aws iam create-instance-profile --instance-profile-name EXAMPLEPROFILENAME

2.    Run the following AWS CLI command to add the role to the instance profile:

$ aws iam add-role-to-instance-profile --instance-profile-name EXAMPLEPROFILENAME --role-name EXAMPLEROLENAME

3.    Run the following AWS CLI command to attach the instance profile to the EC2 instance:

$ aws ec2 associate-iam-instance-profile --iam-instance-profile Name=EXAMPLEPROFILENAME --instance-id i-012345678910abcde

4.    Run the following AWS CLI command to verify that the IAM role is attached to the instance:  

$ aws ec2 describe-iam-instance-profile-associations