Skip to content

How do I assign an existing IAM role to an Amazon EC2 instance?

2 minute read
0

I want to assign an AWS Identity and Access Management (IAM) role to an Amazon Elastic Compute Cloud (Amazon EC2) instance.

Resolution

Note: If you receive errors when you run AWS Command Line Interface (AWS CLI) commands, then see Troubleshooting errors for the AWS CLI. Also, make sure that you're using the most recent AWS CLI version.

Attach the role

Prerequisites:

To assign an IAM role to an EC2 instance, use the Amazon EC2 console or the AWS CLI.

If you use AWS Systems Manager, then wait for the AWS Systems Manager Agent (SSM Agent) to detect the new IAM role. Or, restart SSM Agent.

Validate that you attached the role to the instance

To verify that the instance profile is attached, run the following describe-instances AWS CLI command:

aws ec2 describe-instances --instance-ids i-012345678 --query 'Reservations[0].Instances[0].IamInstanceProfile'

Note: Replace i-012345678 with your instance ID. Make sure that the output shows your instance profile's Amazon Resource Name (ARN) and ID.

To verify that your role is available, connect to your instance, and then run the following command based on your operating system (OS).

Windows:

$token = Invoke-RestMethod -Headers @{"X-aws-ec2-metadata-token-ttl-seconds" = "21600"} -Method PUT -Uri http://169.254.169.254/latest/api/token; Invoke-RestMethod -Headers @{"X-aws-ec2-metadata-token" = $token} -Method GET -Uri http://169.254.169.254/latest/meta-data/iam/security-credentials/

Linux:

TOKEN=$(curl -X PUT "http://169.254.169.254/latest/api/token" -H "X-aws-ec2-metadata-token-ttl-seconds: 21600") && curl -H "X-aws-ec2-metadata-token: $TOKEN" http://169.254.169.254/latest/meta-data/iam/security-credentials/

Note: Make sure that the output shows the role name.

Related information

IAM role creation

Use an IAM role to grant permissions to applications running on Amazon EC2 instances

I created an IAM role, but the role doesn't appear in the dropdown list when I launch an instance. What do I do?

AWS OFFICIALUpdated 6 months ago