

# IAM roles for Amazon EC2
IAM roles

Applications must sign their API requests with AWS credentials. Therefore, if you are an application developer, you need a strategy for managing credentials for your applications that run on EC2 instances. For example, you can securely distribute your AWS credentials to the instances, enabling the applications on those instances to use your credentials to sign requests, while protecting your credentials from other users. However, it's challenging to securely distribute credentials to each instance, especially those that AWS creates on your behalf, such as Spot Instances or instances in Auto Scaling groups. You must also be able to update the credentials on each instance when you rotate your AWS credentials.

We designed IAM roles so that your applications can securely make API requests from your instances, without requiring you to manage the security credentials that the applications use. Instead of creating and distributing your AWS credentials, you can delegate permission to make API requests using IAM roles as follows:

1. Create an IAM role.

1. Define which accounts or AWS services can assume the role.

1. Define which API actions and resources the application can use after assuming the role.

1. Specify the role when you launch your instance, or attach the role to an existing instance.

1. Have the application retrieve a set of temporary credentials and use them.

For example, you can use IAM roles to grant permissions to applications running on your instances that need to use a bucket in Amazon S3. You can specify permissions for IAM roles by creating a policy in JSON format. These are similar to the policies that you create for users. If you change a role, the change is propagated to all instances.

**Note**  
Amazon EC2 IAM role credentials are not subject to maximum session durations configured in the role. For more information, see [Methods to assume a role](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_manage-assume.html) in the *IAM User Guide*.

When creating IAM roles, associate least privilege IAM policies that restrict access to the specific API calls the application requires. For Windows-to-Windows communication, use well-defined and well-documented Windows groups and roles to grant application-level access between Windows instances. Groups and roles allow customers to define least privilege application and NTFS folder-level permissions to limit access to application-specific requirements.

You can only attach one IAM role to an instance, but you can attach the same role to many instances. For more information about creating and using IAM roles, see [Roles](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles.html) in the *IAM User Guide*.

You can apply resource-level permissions to your IAM policies to control the users' ability to attach, replace, or detach IAM roles for an instance. For more information, see [Supported resource-level permissions for Amazon EC2 API actions](iam-policies-for-amazon-ec2.md#ec2-supported-iam-actions-resources) and the following example: [Example: Work with IAM roles](ExamplePolicies_EC2.md#iam-example-iam-roles).

**Topics**
+ [

## Instance profiles
](#ec2-instance-profile)
+ [

## Permissions for your use case
](#generate-policy-for-iam-role)
+ [Retrieve security credentials](instance-metadata-security-credentials.md)
+ [Permissions to attach a role to an instance](permission-to-pass-iam-roles.md)
+ [Attach a role to an instance](attach-iam-role.md)
+ [Instance identity roles](#ec2-instance-identity-roles)

## Instance profiles


Amazon EC2 uses an *instance profile* as a container for an IAM role. When you create an IAM role using the IAM console, the console creates an instance profile automatically and gives it the same name as the role to which it corresponds. If you use the Amazon EC2 console to launch an instance with an IAM role or to attach an IAM role to an instance, you choose the role based on a list of instance profile names. 

If you use the AWS CLI, API, or an AWS SDK to create a role, you create the role and instance profile as separate actions, with potentially different names. If you then use the AWS CLI, API, or an AWS SDK to launch an instance with an IAM role or to attach an IAM role to an instance, specify the instance profile name. 

An instance profile can contain only one IAM role. You can include an IAM role in multiple instance profiles.

To update permissions for an instance, replace its instance profile. We do not recommend removing a role from an instance profile, because there is a delay of up to one hour before this change takes effect.

For more information, see [Use instance profiles](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_use_switch-role-ec2_instance-profiles.html) in the *IAM User Guide*.

## Permissions for your use case


When you first create an IAM role for your applications, you might sometimes grant permissions beyond what is required. Before launching your application in your production environment, you can generate an IAM policy that is based on the access activity for an IAM role. IAM Access Analyzer reviews your AWS CloudTrail logs and generates a policy template that contains the permissions that have been used by the role in your specified date range. You can use the template to create a managed policy with fine-grained permissions and then attach it to the IAM role. That way, you grant only the permissions that the role needs to interact with AWS resources for your specific use case. This helps you adhere to the best practice of [granting least privilege](https://docs.aws.amazon.com/IAM/latest/UserGuide/best-practices.html#grant-least-privilege). For more information, see [IAM Access Analyzer policy generation](https://docs.aws.amazon.com/IAM/latest/UserGuide/access-analyzer-policy-generation.html) in the *IAM User Guide*.

# Retrieve security credentials from instance metadata
Retrieve security credentials

An application on the instance retrieves the security credentials provided by the role from the instance metadata item `iam/security-credentials/`*role-name*. The application is granted the permissions for the actions and resources that you've defined for the role through the security credentials associated with the role. These security credentials are temporary and we rotate them automatically. We make new credentials available at least five minutes before the expiration of the old credentials.

For more information about instance metadata, see [Use instance metadata to manage your EC2 instance](ec2-instance-metadata.md).

**Warning**  
If you use services that use instance metadata with IAM roles, ensure that you don't expose your credentials when the services make HTTP calls on your behalf. The types of services that could expose your credentials include HTTP proxies, HTML/CSS validator services, and XML processors that support XML inclusion.

For your Amazon EC2 workloads, we recommend that you retrieve session credentials using the method described below. These credentials should enable your workload to make AWS API requests, without needing to use `sts:AssumeRole` to assume the same role that is already associated with the instance. Unless you need to pass session tags for attribute-based access control (ABAC) or pass a session policy to further restrict permissions of the role, such role assumption calls are unnecessary as they create a new set of the same temporary role session credentials.

If your workload uses a role to assume itself, you must create a trust policy that explicitly allows that role to assume itself. If you do not create the trust policy, you get an `AccessDenied` error. For more information, see [ Update a role trust policy](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_update-role-trust-policy.html) in the *IAM User Guide*.

------
#### [ IMDSv2 ]

**Linux**  
Run the following command from your Linux instance to retrieve the security credentials for an IAM role.

```
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/role-name
```

**Windows**  
Run the following cmdlet from your Windows instance to retrieve the security credentials for an IAM role.

```
[string]$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/role-name
```

------
#### [ IMDSv1 ]

**Linux**  
Run the following command from your Linux instance to retrieve the security credentials for an IAM role.

```
curl http://169.254.169.254/latest/meta-data/iam/security-credentials/role-name
```

**Windows**  
Run the following cmdlet from your Windows instance to retrieve the security credentials for an IAM role.

```
Invoke-RestMethod -uri http://169.254.169.254/latest/meta-data/iam/security-credentials/role-name
```

------

The following is example output. If you are not able to retrieve the security credentials, see [I can't access the temporary security credentials on my EC2 instance](https://docs.aws.amazon.com/IAM/latest/UserGuide/troubleshoot_iam-ec2.html#troubleshoot_iam-ec2_no-keys) in the *IAM User Guide*.

```
{
  "Code" : "Success",
  "LastUpdated" : "2012-04-26T16:39:16Z",
  "Type" : "AWS-HMAC",
  "AccessKeyId" : "ASIAIOSFODNN7EXAMPLE",
  "SecretAccessKey" : "wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY",
  "Token" : "token",
  "Expiration" : "2017-05-17T15:09:54Z"
}
```

For applications, AWS CLI, and Tools for Windows PowerShell commands that run on the instance, you do not have to explicitly get the temporary security credentials—the AWS SDKs, AWS CLI, and Tools for Windows PowerShell automatically get the credentials from the EC2 instance metadata service and use them. To make a call outside of the instance using temporary security credentials (for example, to test IAM policies), you must provide the access key, secret key, and the session token. For more information, see [Using Temporary Security Credentials to Request Access to AWS Resources](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_temp_use-resources.html) in the *IAM User Guide*.

# Grant permissions to attach an IAM role to an instance
Permissions to attach a role to an instance

The identities in your AWS account, such as IAM users, must have specific permissions to launch an Amazon EC2 instance with an IAM role, attach an IAM role to an instance, replace the IAM role for an instance, or detach an IAM role from an instance. You must grant permission to use the following API actions as required:
+ `iam:PassRole`
+ `ec2:AssociateIamInstanceProfile`
+ `ec2:DisassociateIamInstanceProfile`
+ `ec2:ReplaceIamInstanceProfileAssociation`

**Note**  
If you specify the resource for `iam:PassRole` as `*`, this would grant access to pass any of your IAM roles to an instance. To follow the best practice of [least privilege](https://docs.aws.amazon.com/IAM/latest/UserGuide/best-practices.html#grant-least-privilege), specify the ARNs of specific IAM roles with `iam:PassRole`, as shown in the example policy below.

**Example policy for programmatic access**  
The following IAM policy grants permissions to launch instances with an IAM role, attach an IAM role to an instance, or replace the IAM role for an instance using the AWS CLI or the Amazon EC2 API.

------
#### [ JSON ]

****  

```
{
  "Version":"2012-10-17",		 	 	 
  "Statement": [
    {
      "Effect": "Allow",
      "Action": [
         "ec2:RunInstances",
         "ec2:AssociateIamInstanceProfile",
         "ec2:DisassociateIamInstanceProfile",
         "ec2:ReplaceIamInstanceProfileAssociation"
      ],
      "Resource": "*"
    },
    {
      "Effect": "Allow",
      "Action": "iam:PassRole",
      "Resource": "arn:aws:iam::123456789012:role/DevTeam*"
    }
  ]
}
```

------

**Additional requirement for console access**  
To grant permissions to complete the same tasks using the Amazon EC2 console, you must also include the `iam:ListInstanceProfiles` API action.

# Attach an IAM role to an instance
Attach a role to an instance

You can create an IAM role and attach it to an instance during or after launch. You can also replace or detach IAM roles.

**Creating and attaching an IAM role during instance launch (Recommended)**

1. During EC2 instance launch, expand **Advanced details**.

1. In the **IAM instance profile** section, choose **Create new IAM role**.

1. An inline role creation form opens, allowing you to:
   + Specify **Role name** (for example, `EC2-S3-Access-Role`)
   + Define permissions by selecting AWS managed policies or creating custom policies for your instance

     For example, to grant S3 access, select the `AmazonS3ReadOnlyAccess` managed policy
   + Review the trust policy that allows `ec2.amazonaws.com` to assume the role
   + Add optional tags for metadata

1. Choose **Create role**.

   The newly created role is automatically selected and will be attached to your instance via an instance profile when the instance launches.

**Note**  
When you create a role using the console during instance launch, an instance profile with the same name as the role is automatically created. The instance profile is a container that passes IAM role information to the instance at launch.

**Important**  
You can only attach one IAM role to an instance, but you can attach the same role to many instances.
Associate least privilege IAM policies that restrict access to the specific API calls the application requires.

For more information about creating and using IAM roles, see [Roles](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles.html) in the *IAM User Guide*.

**Attaching an existing IAM role during instance launch**  
To attach an existing IAM role to an instance at launch using the Amazon EC2 console, expand **Advanced details**. For **IAM instance profile**, select the IAM role from the dropdown list.

**Note**  
If you created your IAM role using the IAM console, the instance profile was created for you and given the same name as the role. If you created your IAM role using the AWS CLI, API, or an AWS SDK, you might have given your instance profile a different name than the role.

You can attach an IAM role to an instance that is running or stopped. If the instance already has an IAM role attached, you must replace it with the new IAM role.

------
#### [ Console ]<a name="attach-iam-role-console"></a>

**To attach an IAM role to an instance**

1. Open the Amazon EC2 console at [https://console.aws.amazon.com/ec2/](https://console.aws.amazon.com/ec2/).

1. In the navigation pane, choose **Instances**.

1. Select the instance.

1. Choose **Actions**, **Security**, **Modify IAM role**.

1. For **IAM role**, select the IAM instance profile.

1. Choose **Update IAM role**.

------
#### [ AWS CLI ]
<a name="attach-iam-role-instance-cli"></a>
**To attach an IAM role to an instance**  
Use the [associate-iam-instance-profile](https://docs.aws.amazon.com/cli/latest/reference/ec2/associate-iam-instance-profile.html) command to attach the IAM role to the instance. When you specify the instance profile, you can use either the Amazon Resource Name (ARN) of the instance profile, or you can use its name.

```
aws ec2 associate-iam-instance-profile \
    --instance-id i-1234567890abcdef0 \
    --iam-instance-profile Name="TestRole-1"
```

------
#### [ PowerShell ]

**To attach an IAM role to an instance**  
Use the [Register-EC2IamInstanceProfile](https://docs.aws.amazon.com/powershell/latest/reference/items/Register-EC2IamInstanceProfile.html) cmdlet.

```
Register-EC2IamInstanceProfile `
    -InstanceId i-1234567890abcdef0 `
    -IamInstanceProfile_Name TestRole-1
```

------

To replace the IAM role on an instance that already has an attached IAM role, the instance must be running. You can do this if you want to change the IAM role for an instance without detaching the existing one first. For example, you can do this to ensure that API actions performed by applications running on the instance are not interrupted.

------
#### [ Console ]<a name="replace-iam-role-console"></a>

**To replace an IAM role for an instance**

1. Open the Amazon EC2 console at [https://console.aws.amazon.com/ec2/](https://console.aws.amazon.com/ec2/).

1. In the navigation pane, choose **Instances**.

1. Select the instance.

1. Choose **Actions**, **Security**, **Modify IAM role**.

1. For **IAM role**, select the IAM instance profile.

1. Choose **Update IAM role**.

------
#### [ AWS CLI ]<a name="replace-iam-role-cli"></a>

**To replace an IAM role for an instance**

1. If required, use the [describe-iam-instance-profile-associations](https://docs.aws.amazon.com/cli/latest/reference/ec2/describe-iam-instance-profile-associations.html) command to get the association ID.

   ```
   aws ec2 describe-iam-instance-profile-associations \
       --filters Name=instance-id,Values=i-1234567890abcdef0 \
       --query IamInstanceProfileAssociations.AssociationId
   ```

1. Use the [replace-iam-instance-profile-association](https://docs.aws.amazon.com/cli/latest/reference/ec2/replace-iam-instance-profile-association.html) command. Specify the association ID for the existing instance profile and the ARN or name of the new instance profile.

   ```
   aws ec2 replace-iam-instance-profile-association \
       --association-id iip-assoc-0044d817db6c0a4ba \
       --iam-instance-profile Name="TestRole-2"
   ```

------
#### [ PowerShell ]

**To replace an IAM role for an instance**

1. If required, use the [Get-EC2IamInstanceProfileAssociation](https://docs.aws.amazon.com/powershell/latest/reference/items/Get-EC2IamInstanceProfileAssociation.html) cmdlet to get the association ID.

   ```
   (Get-EC2IamInstanceProfileAssociation -Filter @{Name="instance-id"; Values="i-0636508011d8e966a"}).AssociationId
   ```

1. Use the [Set-EC2IamInstanceProfileAssociation](https://docs.aws.amazon.com/powershell/latest/reference/items/Set-EC2IamInstanceProfileAssociation.html) cmdlet. Specify the association ID for the existing instance profile and the ARN or name of the new instance profile.

   ```
   Set-EC2IamInstanceProfileAssociation `
       -AssociationId iip-assoc-0044d817db6c0a4ba `
       -IamInstanceProfile_Name TestRole-2
   ```

------

You can detach an IAM role from an instance that is running or stopped.

------
#### [ Console ]<a name="detach-iam-role-console"></a>

**To detach an IAM role from an instance**

1. Open the Amazon EC2 console at [https://console.aws.amazon.com/ec2/](https://console.aws.amazon.com/ec2/).

1. In the navigation pane, choose **Instances**.

1. Select the instance.

1. Choose **Actions**, **Security**, **Modify IAM role**.

1. For **IAM role**, choose **No IAM Role**.

1. Choose **Update IAM role**.

1. When promoted for confirmation, enter **Detach**, and then choose **Detach**.

------
#### [ AWS CLI ]<a name="detach-iam-role-cli"></a>

**To detach an IAM role from an instance**

1. If required, use [describe-iam-instance-profile-associations](https://docs.aws.amazon.com/cli/latest/reference/ec2/describe-iam-instance-profile-associations.html) to get the association ID for the IAM instance profile to detach.

   ```
   aws ec2 describe-iam-instance-profile-associations \
       --filters Name=instance-id,Values=i-1234567890abcdef0 \
       --query IamInstanceProfileAssociations.AssociationId
   ```

1. Use the [disassociate-iam-instance-profile](https://docs.aws.amazon.com/cli/latest/reference/ec2/disassociate-iam-instance-profile.html) command.

   ```
   aws ec2 disassociate-iam-instance-profile --association-id iip-assoc-0044d817db6c0a4ba
   ```

------
#### [ PowerShell ]

**To detach an IAM role from an instance**

1. If required, use [Get-EC2IamInstanceProfileAssociation](https://docs.aws.amazon.com/powershell/latest/reference/items/Get-EC2IamInstanceProfileAssociation.html) to get the association ID for the IAM instance profile to detach.

   ```
   (Get-EC2IamInstanceProfileAssociation -Filter @{Name="instance-id"; Values="i-0636508011d8e966a"}).AssociationId
   ```

1. Use the [Unregister-EC2IamInstanceProfile](https://docs.aws.amazon.com/powershell/latest/reference/items/Unregister-EC2IamInstanceProfile.html) cmdlet.

   ```
   Unregister-EC2IamInstanceProfile -AssociationId iip-assoc-0044d817db6c0a4ba
   ```

------

## Instance identity roles for Amazon EC2 instances
Instance identity roles

Each Amazon EC2 instance that you launch has an *instance identity role* that represents its identity. An instance identity role is a type of IAM role. AWS services and features that are integrated to use the instance identity role can use it to identify the instance to the service.

The instance identity role credentials are accessible from the Instance Metadata Service (IMDS) at `/identity-credentials/ec2/security-credentials/ec2-instance`. The credentials consist of an AWS temporary access key pair and a session token. They are used to sign AWS Sigv4 requests to the AWS services that use the instance identity role. The credentials are present in the instance metadata regardless of whether a service or feature that makes use of instance identity roles is enabled on the instance.

Instance identity roles are automatically created when an instance is launched, have no role-trust policy document, and are not subject to any identity or resource policy.

### Supported services


The following AWS services use the instance identity role:
+ **Amazon EC2** – [EC2 Instance Connect](connect-linux-inst-eic.md) uses the instance identity role to update the host keys for a Linux instance.
+ **Amazon GuardDuty** – [GuardDuty Runtime Monitoring](https://docs.aws.amazon.com/guardduty/latest/ug/runtime-monitoring.html) uses the instance identity role to allow the runtime agent to send security telemetry to the GuardDuty VPC endpoint.
+ **AWS Lambda** – [Lambda Managed Instances](https://docs.aws.amazon.com/lambda/latest/dg/lambda-managed-instances.html) uses the instance identity role for lifecycle hooks, telemetry, and artifact distribution.
+ **AWS Security Token Service (AWS STS)** – Instance identity role credentials can be used with the AWS STS [https://docs.aws.amazon.com/STS/latest/APIReference/API_GetCallerIdentity.html](https://docs.aws.amazon.com/STS/latest/APIReference/API_GetCallerIdentity.html) action.
+ **AWS Systems Manager** – When using [Default Host Management Configuration](https://docs.aws.amazon.com/systems-manager/latest/userguide/fleet-manager-default-host-management-configuration.html), AWS Systems Manager uses the identity provided by the instance identity role to register EC2 instances. After identifying your instance, Systems Manager can pass your `AWSSystemsManagerDefaultEC2InstanceManagementRole` IAM role to your instance.

Instance identity roles can’t be used with other AWS services or features because they do not have an integration with instance identity roles.

### Instance identity role ARN


The instance identity role ARN takes the following format:

```
arn:aws-partition:iam::account-number:assumed-role/aws:ec2-instance/instance-id
```

For example:

```
arn:aws:iam::0123456789012:assumed-role/aws:ec2-instance/i-1234567890abcdef0
```

For more information about ARNs, see [Amazon Resource Names (ARNs)](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference-arns.html) in the *IAM User Guide*.