IAM roles for Amazon EC2 - Amazon Elastic Compute Cloud

IAM roles for Amazon EC2

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.

Note

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 the AccessDenied error. For more information, see Modifying a role trust policy in the IAM User Guide.

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.

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

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

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

  5. 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 Using IAM roles in the IAM User Guide.

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 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 and the following example: Example: Work with IAM 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. This limit cannot be increased.

For more information, see Instance Profiles in the IAM User Guide.

Retrieve security credentials from instance metadata

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.

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.

The following command retrieves the security credentials for an IAM role named s3access.

IMDSv2
PS C:\> [string]$token = Invoke-RestMethod -Headers @{"X-aws-ec2-metadata-token-ttl-seconds" = "21600"} -Method PUT -Uri http://169.254.169.254/latest/api/token
PS C:\> Invoke-RestMethod -Headers @{"X-aws-ec2-metadata-token" = $token} -Method GET -Uri http://169.254.169.254/latest/meta-data/iam/security-credentials/s3access
IMDSv1
PS C:\> Invoke-RestMethod -uri http://169.254.169.254/latest/meta-data/iam/security-credentials/s3access

The following is example output.

{ "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 in the IAM User Guide.

For more information about instance metadata, see Instance metadata and user data. For information about the instance metadata IP address, see Retrieve instance metadata.

Grant a user permission to pass an IAM role to an instance

To enable a user to launch an instance with an IAM role or to attach or replace an IAM role for an existing instance, you must grant the user permission to use the following API actions:

  • iam:PassRole

  • ec2:AssociateIamInstanceProfile

  • ec2:ReplaceIamInstanceProfileAssociation

For example, the following IAM policy grants users permission to launch instances with an IAM role, or to attach or replace an IAM role for an existing instance using the AWS CLI.

Note

If you want the policy to grant users access to all of your roles, specify the resource as * in the policy. However, please consider the principle of least privilege as a best-practice .

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

To grant users permission to launch instances with an IAM role, or to attach or replace an IAM role for an existing instance using the Amazon EC2 console, you must grant them permission to use iam:ListInstanceProfiles, iam:PassRole, ec2:AssociateIamInstanceProfile, and ec2:ReplaceIamInstanceProfileAssociation in addition to any other permissions they might need. For example policies, see Example policies for working in the Amazon EC2 console.

Work with IAM roles

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

Create an IAM role

You must create an IAM role before you can launch an instance with that role or attach it to an instance.

Console
To create an IAM role using the IAM console
  1. Open the IAM console at https://console.aws.amazon.com/iam/.

  2. In the navigation pane, choose Roles then choose Create role.

  3. On the Select trusted entity page, choose AWS service, and then select the EC2 use case. Choose Next.

  4. On the Add permissions page, select the policies that grants your instances access to the resources that they need. Choose Next.

  5. On the Name, review, and create page, enter a name and description for the role. Optionally, add tags to the role. Choose Create role.

Command line

The following example creates an IAM role with a policy that allows the role to use an Amazon S3 bucket.

To create an IAM role and instance profile (AWS CLI)
  1. Create the following trust policy and save it in a text file named ec2-role-trust-policy.json.

    { "Version": "2012-10-17", "Statement": [ { "Effect": "Allow", "Principal": { "Service": "ec2.amazonaws.com"}, "Action": "sts:AssumeRole" } ] }
  2. Create the s3access role and specify the trust policy that you created using the create-role command.

    aws iam create-role \ --role-name s3access \ --assume-role-policy-document file://ec2-role-trust-policy.json

    Example response

    { "Role": { "AssumeRolePolicyDocument": { "Version": "2012-10-17", "Statement": [ { "Action": "sts:AssumeRole", "Effect": "Allow", "Principal": { "Service": "ec2.amazonaws.com" } } ] }, "RoleId": "AROAIIZKPBKS2LEXAMPLE", "CreateDate": "2013-12-12T23:46:37.247Z", "RoleName": "s3access", "Path": "/", "Arn": "arn:aws:iam::123456789012:role/s3access" } }
  3. Create an access policy and save it in a text file named ec2-role-access-policy.json. For example, this policy grants administrative permissions for Amazon S3 to applications running on the instance.

    { "Version": "2012-10-17", "Statement": [ { "Effect": "Allow", "Action": ["s3:*"], "Resource": ["*"] } ] }
  4. Attach the access policy to the role using the put-role-policy command.

    aws iam put-role-policy \ --role-name s3access \ --policy-name S3-Permissions \ --policy-document file://ec2-role-access-policy.json
  5. Create an instance profile named s3access-profile using the create-instance-profile command.

    aws iam create-instance-profile --instance-profile-name s3access-profile

    Example response

    { "InstanceProfile": { "InstanceProfileId": "AIPAJTLBPJLEGREXAMPLE", "Roles": [], "CreateDate": "2013-12-12T23:53:34.093Z", "InstanceProfileName": "s3access-profile", "Path": "/", "Arn": "arn:aws:iam::123456789012:instance-profile/s3access-profile" } }
  6. Add the s3access role to the s3access-profile instance profile.

    aws iam add-role-to-instance-profile \ --instance-profile-name s3access-profile \ --role-name s3access

Alternatively, you can use the following AWS Tools for Windows PowerShell commands:

Launch an instance with an IAM role

After you've created an IAM role, you can launch an instance, and associate that role with the instance during launch.

Important

After you create an IAM role, it might take several seconds for the permissions to propagate. If your first attempt to launch an instance with a role fails, wait a few seconds before trying again. For more information, see Troubleshooting IAM roles in the IAM User Guide.

New console
To launch an instance with an IAM role (console)
  1. Follow the procedure to launch an instance.

  2. Expand Advanced details, and for IAM instance profile, select the IAM role that you created.

    Note

    The IAM instance profile list displays the name of the instance profile that you created when you created your IAM role. If you created your IAM role using the 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 may have named your instance profile differently.

  3. Configure any other details that you require for your instance or accept the defaults, and select a key pair. For information about the fields in the launch instance wizard, see Launch an instance using defined parameters.

  4. In the Summary panel, review your instance configuration, and then choose Launch instance.

  5. If you are using the Amazon EC2 API actions in your application, retrieve the AWS security credentials made available on the instance and use them to sign the requests. The AWS SDK does this for you.

    IMDSv2IMDSv1
    IMDSv2
    PS C:\> [string]$token = Invoke-RestMethod -Headers @{"X-aws-ec2-metadata-token-ttl-seconds" = "21600"} -Method PUT -Uri http://169.254.169.254/latest/api/token
    PS C:\> 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
    PS C:\> Invoke-RestMethod -uri http://169.254.169.254/latest/meta-data/iam/security-credentials/role_name
Old console
To launch an instance with an IAM role (console)
  1. Open the Amazon EC2 console at https://console.aws.amazon.com/ec2/.

  2. On the dashboard, choose Launch instance.

  3. Select an AMI and instance type and then choose Next: Configure Instance Details.

  4. On the Configure Instance Details page, for IAM role, select the IAM role that you created.

    Note

    The IAM role list displays the name of the instance profile that you created when you created your IAM role. If you created your IAM role using the 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 may have named your instance profile differently.

  5. Configure any other details, then follow the instructions through the rest of the wizard, or choose Review and Launch to accept default settings and go directly to the Review Instance Launch page.

  6. Review your settings, then choose Launch to choose a key pair and launch your instance.

  7. If you are using the Amazon EC2 API actions in your application, retrieve the AWS security credentials made available on the instance and use them to sign the requests. The AWS SDK does this for you.

    IMDSv2IMDSv1
    IMDSv2
    PS C:\> [string]$token = Invoke-RestMethod -Headers @{"X-aws-ec2-metadata-token-ttl-seconds" = "21600"} -Method PUT -Uri http://169.254.169.254/latest/api/token
    PS C:\> 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
    PS C:\> Invoke-RestMethod -uri http://169.254.169.254/latest/meta-data/iam/security-credentials/role_name
Command line

You can use the AWS CLI to associate a role with an instance during launch. You must specify the instance profile in the command.

To launch an instance with an IAM role (AWS CLI)
  1. Use the run-instances command to launch an instance using the instance profile. The following example shows how to launch an instance with the instance profile.

    aws ec2 run-instances \ --image-id ami-11aa22bb \ --iam-instance-profile Name="s3access-profile" \ --key-name my-key-pair \ --security-groups my-security-group \ --subnet-id subnet-1a2b3c4d

    Alternatively, use the New-EC2Instance Tools for Windows PowerShell command.

  2. If you are using the Amazon EC2 API actions in your application, retrieve the AWS security credentials made available on the instance and use them to sign the requests. The AWS SDK does this for you.

    curl http://169.254.169.254/latest/meta-data/iam/security-credentials/role_name

Attach an IAM role to an instance

To attach an IAM role to an instance that has no role, the instance can be in the stopped or running state.

Console
To attach an IAM role to an instance
  1. Open the Amazon EC2 console at https://console.aws.amazon.com/ec2/.

  2. In the navigation pane, choose Instances.

  3. Select the instance, choose Actions, Security, Modify IAM role.

  4. Select the IAM role to attach to your instance, and choose Save.

Command line
To attach an IAM role to an instance (AWS CLI)
  1. If required, describe your instances to get the ID of the instance to which to attach the role.

    aws ec2 describe-instances
  2. Use the associate-iam-instance-profile command to attach the IAM role to the instance by specifying the instance profile. You can use 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"

    Example response

    { "IamInstanceProfileAssociation": { "InstanceId": "i-1234567890abcdef0", "State": "associating", "AssociationId": "iip-assoc-0dbd8529a48294120", "IamInstanceProfile": { "Id": "AIPAJLNLDX3AMYZNWYYAY", "Arn": "arn:aws:iam::123456789012:instance-profile/TestRole-1" } } }

Alternatively, use the following Tools for Windows PowerShell commands:

Replace an IAM role

To replace the IAM role on an instance that already has an attached IAM role, the instance must be in the running state. 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
To replace an IAM role for an instance
  1. Open the Amazon EC2 console at https://console.aws.amazon.com/ec2/.

  2. In the navigation pane, choose Instances.

  3. Select the instance, choose Actions, Security, Modify IAM role.

  4. Select the IAM role to attach to your instance, and choose Save.

Command line
To replace an IAM role for an instance (AWS CLI)
  1. If required, describe your IAM instance profile associations to get the association ID for the IAM instance profile to replace.

    aws ec2 describe-iam-instance-profile-associations
  2. Use the replace-iam-instance-profile-association command to replace the IAM instance profile by specifying the association ID for the existing instance profile and the ARN or name of the instance profile that should replace it.

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

    Example response

    { "IamInstanceProfileAssociation": { "InstanceId": "i-087711ddaf98f9489", "State": "associating", "AssociationId": "iip-assoc-09654be48e33b91e0", "IamInstanceProfile": { "Id": "AIPAJCJEDKX7QYHWYK7GS", "Arn": "arn:aws:iam::123456789012:instance-profile/TestRole-2" } } }

Alternatively, use the following Tools for Windows PowerShell commands:

Detach an IAM role

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

Console
To detach an IAM role from an instance
  1. Open the Amazon EC2 console at https://console.aws.amazon.com/ec2/.

  2. In the navigation pane, choose Instances.

  3. Select the instance, choose Actions, Security, Modify IAM role.

  4. For IAM role, choose No IAM Role. Choose Save.

  5. In the confirmation dialog box, enter Detach, and then choose Detach.

Command line
To detach an IAM role from an instance (AWS CLI)
  1. If required, use describe-iam-instance-profile-associations to describe your IAM instance profile associations and get the association ID for the IAM instance profile to detach.

    aws ec2 describe-iam-instance-profile-associations

    Example response

    { "IamInstanceProfileAssociations": [ { "InstanceId": "i-088ce778fbfeb4361", "State": "associated", "AssociationId": "iip-assoc-0044d817db6c0a4ba", "IamInstanceProfile": { "Id": "AIPAJEDNCAA64SSD265D6", "Arn": "arn:aws:iam::123456789012:instance-profile/TestRole-2" } } ] }
  2. Use the disassociate-iam-instance-profile command to detach the IAM instance profile using its association ID.

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

    Example response

    { "IamInstanceProfileAssociation": { "InstanceId": "i-087711ddaf98f9489", "State": "disassociating", "AssociationId": "iip-assoc-0044d817db6c0a4ba", "IamInstanceProfile": { "Id": "AIPAJEDNCAA64SSD265D6", "Arn": "arn:aws:iam::123456789012:instance-profile/TestRole-2" } } }

Alternatively, use the following Tools for Windows PowerShell commands:

Generate a policy for your IAM role based on access activity

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. To learn more, see Generate policies based on access activity in the IAM User Guide.