

# Identity and Access Management for Amazon Elastic Container Service
Identity and Access Management

 

 

AWS Identity and Access Management (IAM) is an AWS service that helps an administrator securely control access to AWS resources. IAM administrators control who can be *authenticated* (signed in) and *authorized* (have permissions) to use Amazon ECS resources. IAM is an AWS service that you can use with no additional charge.

**Topics**
+ [

## Audience
](#security_iam_audience)
+ [

## Authenticating with identities
](#security_iam_authentication)
+ [

## Managing access using policies
](#security_iam_access-manage)
+ [

# How Amazon Elastic Container Service works with IAM
](security_iam_service-with-iam.md)
+ [

# Identity-based policy examples for Amazon Elastic Container Service
](security_iam_id-based-policy-examples.md)
+ [

# AWS managed policies for Amazon Elastic Container Service
](security-iam-awsmanpol.md)
+ [

# Using service-linked roles for Amazon ECS
](using-service-linked-roles.md)
+ [

# IAM roles for Amazon ECS
](security-ecs-iam-role-overview.md)
+ [

# Permissions required for the Amazon ECS console
](console-permissions.md)
+ [

# Permissions required for Lambda functions in Amazon ECS blue/green deployments
](blue-green-permissions.md)
+ [

# IAM permissions required for Amazon ECS service auto scaling
](auto-scaling-IAM.md)
+ [

# Grant permission to tag resources on creation
](supported-iam-actions-tagging.md)
+ [

# Troubleshooting Amazon Elastic Container Service identity and access
](security_iam_troubleshoot.md)
+ [

# IAM best practices for Amazon ECS
](security-iam-bestpractices.md)

## Audience


How you use AWS Identity and Access Management (IAM) differs based on your role:
+ **Service user** - request permissions from your administrator if you cannot access features (see [Troubleshooting Amazon Elastic Container Service identity and access](security_iam_troubleshoot.md))
+ **Service administrator** - determine user access and submit permission requests (see [How Amazon Elastic Container Service works with IAM](security_iam_service-with-iam.md))
+ **IAM administrator** - write policies to manage access (see [Identity-based policy examples for Amazon Elastic Container Service](security_iam_id-based-policy-examples.md))

## Authenticating with identities


Authentication is how you sign in to AWS using your identity credentials. You must be authenticated as the AWS account root user, an IAM user, or by assuming an IAM role.

You can sign in as a federated identity using credentials from an identity source like AWS IAM Identity Center (IAM Identity Center), single sign-on authentication, or Google/Facebook credentials. For more information about signing in, see [How to sign in to your AWS account](https://docs.aws.amazon.com/signin/latest/userguide/how-to-sign-in.html) in the *AWS Sign-In User Guide*.

For programmatic access, AWS provides an SDK and CLI to cryptographically sign requests. For more information, see [AWS Signature Version 4 for API requests](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_sigv.html) in the *IAM User Guide*.

### AWS account root user


 When you create an AWS account, you begin with one sign-in identity called the AWS account *root user* that has complete access to all AWS services and resources. We strongly recommend that you don't use the root user for everyday tasks. For tasks that require root user credentials, see [Tasks that require root user credentials](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_root-user.html#root-user-tasks) in the *IAM User Guide*. 

### Federated identity


As a best practice, require human users to use federation with an identity provider to access AWS services using temporary credentials.

A *federated identity* is a user from your enterprise directory, web identity provider, or Directory Service that accesses AWS services using credentials from an identity source. Federated identities assume roles that provide temporary credentials.

For centralized access management, we recommend AWS IAM Identity Center. For more information, see [What is IAM Identity Center?](https://docs.aws.amazon.com/singlesignon/latest/userguide/what-is.html) in the *AWS IAM Identity Center User Guide*.

### IAM users and groups


An *[IAM user](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_users.html)* is an identity with specific permissions for a single person or application. We recommend using temporary credentials instead of IAM users with long-term credentials. For more information, see [Require human users to use federation with an identity provider to access AWS using temporary credentials](https://docs.aws.amazon.com/IAM/latest/UserGuide/best-practices.html#bp-users-federation-idp) in the *IAM User Guide*.

An [https://docs.aws.amazon.com/IAM/latest/UserGuide/id_groups.html](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_groups.html) specifies a collection of IAM users and makes permissions easier to manage for large sets of users. For more information, see [Use cases for IAM users](https://docs.aws.amazon.com/IAM/latest/UserGuide/gs-identities-iam-users.html) in the *IAM User Guide*.

### IAM roles


An *[IAM role](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles.html)* is an identity with specific permissions that provides temporary credentials. You can assume a role by [switching from a user to an IAM role (console)](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_use_switch-role-console.html) or by calling an AWS CLI or AWS API operation. 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*.

IAM roles are useful for federated user access, temporary IAM user permissions, cross-account access, cross-service access, and applications running on Amazon EC2. For more information, see [Cross account resource access in IAM](https://docs.aws.amazon.com/IAM/latest/UserGuide/access_policies-cross-account-resource-access.html) in the *IAM User Guide*.

## Managing access using policies


You control access in AWS by creating policies and attaching them to AWS identities or resources. A policy defines permissions when associated with an identity or resource. AWS evaluates these policies when a principal makes a request. Most policies are stored in AWS as JSON documents. For more information about JSON policy documents, see [Overview of JSON policies](https://docs.aws.amazon.com/IAM/latest/UserGuide/access_policies.html#access_policies-json) in the *IAM User Guide*.

Using policies, administrators specify who has access to what by defining which **principal** can perform **actions** on what **resources**, and under what **conditions**.

By default, users and roles have no permissions. An IAM administrator creates IAM policies and adds them to roles, which users can then assume. IAM policies define permissions regardless of the method used to perform the operation.

### Identity-based policies


Identity-based policies are JSON permissions policy documents that you attach to an identity (user, group, or role). These policies control what actions identities can perform, on which resources, and under what conditions. To learn how to create an identity-based policy, see [Define custom IAM permissions with customer managed policies](https://docs.aws.amazon.com/IAM/latest/UserGuide/access_policies_create.html) in the *IAM User Guide*.

Identity-based policies can be *inline policies* (embedded directly into a single identity) or *managed policies* (standalone policies attached to multiple identities). To learn how to choose between managed and inline policies, see [Choose between managed policies and inline policies](https://docs.aws.amazon.com/IAM/latest/UserGuide/access_policies-choosing-managed-or-inline.html) in the *IAM User Guide*.

### Resource-based policies


Resource-based policies are JSON policy documents that you attach to a resource. Examples include IAM *role trust policies* and Amazon S3 *bucket policies*. In services that support resource-based policies, service administrators can use them to control access to a specific resource. You must [specify a principal](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_principal.html) in a resource-based policy.

Resource-based policies are inline policies that are located in that service. You can't use AWS managed policies from IAM in a resource-based policy.

### Other policy types


AWS supports additional policy types that can set the maximum permissions granted by more common policy types:
+ **Permissions boundaries** – Set the maximum permissions that an identity-based policy can grant to an IAM entity. For more information, see [Permissions boundaries for IAM entities](https://docs.aws.amazon.com/IAM/latest/UserGuide/access_policies_boundaries.html) in the *IAM User Guide*.
+ **Service control policies (SCPs)** – Specify the maximum permissions for an organization or organizational unit in AWS Organizations. For more information, see [Service control policies](https://docs.aws.amazon.com/organizations/latest/userguide/orgs_manage_policies_scps.html) in the *AWS Organizations User Guide*.
+ **Resource control policies (RCPs)** – Set the maximum available permissions for resources in your accounts. For more information, see [Resource control policies (RCPs)](https://docs.aws.amazon.com/organizations/latest/userguide/orgs_manage_policies_rcps.html) in the *AWS Organizations User Guide*.
+ **Session policies** – Advanced policies passed as a parameter when creating a temporary session for a role or federated user. For more information, see [Session policies](https://docs.aws.amazon.com/IAM/latest/UserGuide/access_policies.html#policies_session) in the *IAM User Guide*.

### Multiple policy types


When multiple types of policies apply to a request, the resulting permissions are more complicated to understand. To learn how AWS determines whether to allow a request when multiple policy types are involved, see [Policy evaluation logic](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_evaluation-logic.html) in the *IAM User Guide*.

# How Amazon Elastic Container Service works with IAM


Before you use IAM to manage access to Amazon ECS, learn what IAM features are available to use with Amazon ECS.

 

 


| IAM feature | Amazon ECS support | 
| --- | --- | 
|   [Identity-based policies](#security_iam_service-with-iam-id-based-policies)   |   Yes  | 
|   [Resource-based policies](#security_iam_service-with-iam-resource-based-policies)   |   No   | 
|   [Policy actions](#security_iam_service-with-iam-id-based-policies-actions)   |   Yes  | 
|   [Policy resources](#security_iam_service-with-iam-id-based-policies-resources)   |   Partial  | 
|   [Policy condition keys](#security_iam_service-with-iam-id-based-policies-conditionkeys)   |   Yes  | 
|   [ACLs](#security_iam_service-with-iam-acls)   |   No   | 
|   [ABAC (tags in policies)](#security_iam_service-with-iam-tags)   |   Yes  | 
|   [Temporary credentials](#security_iam_service-with-iam-roles-tempcreds)   |   Yes  | 
|   [Forward access sessions (FAS)](#security_iam_service-with-iam-principal-permissions)   |   Yes  | 
|   [Service roles](#security_iam_service-with-iam-roles-service)   |   Yes  | 
|   [Service-linked roles](#security_iam_service-with-iam-roles-service-linked)   |   Yes  | 

To get a high-level view of how Amazon ECS and other AWS services work with most IAM features, see [AWS services that work with IAM](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_aws-services-that-work-with-iam.html) in the *IAM User Guide*.

## Identity-based policies for Amazon ECS
Identity-based policies

**Supports identity-based policies:** Yes

Identity-based policies are JSON permissions policy documents that you can attach to an identity, such as an IAM user, group of users, or role. These policies control what actions users and roles can perform, on which resources, and under what conditions. To learn how to create an identity-based policy, see [Define custom IAM permissions with customer managed policies](https://docs.aws.amazon.com/IAM/latest/UserGuide/access_policies_create.html) in the *IAM User Guide*.

With IAM identity-based policies, you can specify allowed or denied actions and resources as well as the conditions under which actions are allowed or denied. To learn about all of the elements that you can use in a JSON policy, see [IAM JSON policy elements reference](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements.html) in the *IAM User Guide*.

### Identity-based policy examples for Amazon ECS
IAM policies

 

To view examples of Amazon ECS identity-based policies, see [Identity-based policy examples for Amazon Elastic Container Service](security_iam_id-based-policy-examples.md).

## Resource-based policies within Amazon ECS
Resource-based policies

**Supports resource-based policies:** No 

Resource-based policies are JSON policy documents that you attach to a resource. Examples of resource-based policies are IAM *role trust policies* and Amazon S3 *bucket policies*. In services that support resource-based policies, service administrators can use them to control access to a specific resource. For the resource where the policy is attached, the policy defines what actions a specified principal can perform on that resource and under what conditions. You must [specify a principal](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_principal.html) in a resource-based policy. Principals can include accounts, users, roles, federated users, or AWS services.

To enable cross-account access, you can specify an entire account or IAM entities in another account as the principal in a resource-based policy. For more information, see [Cross account resource access in IAM](https://docs.aws.amazon.com/IAM/latest/UserGuide/access_policies-cross-account-resource-access.html) in the *IAM User Guide*.

## Policy actions for Amazon ECS
Policy actions

**Supports policy actions:** Yes

Administrators can use AWS JSON policies to specify who has access to what. That is, which **principal** can perform **actions** on what **resources**, and under what **conditions**.

The `Action` element of a JSON policy describes the actions that you can use to allow or deny access in a policy. Include actions in a policy to grant permissions to perform the associated operation.

 

To see a list of Amazon ECS actions, see [Actions defined by Amazon Elastic Container Service](https://docs.aws.amazon.com/service-authorization/latest/reference/list_amazonelasticcontainerservice.html#amazonelasticcontainerservice-actions-as-permissions) in the *Service Authorization Reference*.

Policy actions in Amazon ECS use the following prefix before the action:

```
ecs
```

To specify multiple actions in a single statement, separate them with commas.

```
"Action": [
      "ecs:action1",
      "ecs:action2"
         ]
```

 

 

You can specify multiple actions using wildcards (\$1). For example, to specify all actions that begin with the word `Describe`, include the following action:

```
"Action": "ecs:Describe*"
```

To view examples of Amazon ECS identity-based policies, see [Identity-based policy examples for Amazon Elastic Container Service](security_iam_id-based-policy-examples.md).

## Policy resources for Amazon ECS
Policy resources

**Supports policy resources:** Partial

Administrators can use AWS JSON policies to specify who has access to what. That is, which **principal** can perform **actions** on what **resources**, and under what **conditions**.

The `Resource` JSON policy element specifies the object or objects to which the action applies. As a best practice, specify a resource using its [Amazon Resource Name (ARN)](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference-arns.html). For actions that don't support resource-level permissions, use a wildcard (\$1) to indicate that the statement applies to all resources.

```
"Resource": "*"
```

To see a list of Amazon ECS resource types and their ARNs, see [Resources defined by Amazon Elastic Container Service](https://docs.aws.amazon.com/service-authorization/latest/reference/list_amazonelasticcontainerservice.html#amazonelasticcontainerservice-resources-for-iam-policies) in the *Service Authorization Reference*. To learn with which actions you can specify the ARN of each resource, see [Actions defined by Amazon Elastic Container Service](https://docs.aws.amazon.com/service-authorization/latest/reference/list_amazonelasticcontainerservice.html#amazonelasticcontainerservice-actions-as-permissions).

 

 

Some Amazon ECS API actions support multiple resources. For example, multiple clusters can be referenced when calling the `DescribeClusters` API action. To specify multiple resources in a single statement, separate the ARNs with commas. 

```
"Resource": [
      "EXAMPLE-RESOURCE-1",
      "EXAMPLE-RESOURCE-2"
```

For example, the Amazon ECS cluster resource has the following ARN:

```
arn:${Partition}:ecs:${Region}:${Account}:cluster/${clusterName}
```

To specify `my-cluster-1` and `my-cluster-2` cluster in your statement, use the following ARNs:

```
"Resource": [
         "arn:aws:ecs:us-east-1:123456789012:cluster/my-cluster-1",
         "arn:aws:ecs:us-east-1:123456789012:cluster/my-cluster-2"
```

To specify all clusters that belong to a specific account, use the wildcard (\$1):

```
"Resource": "arn:aws:ecs:us-east-1:123456789012:cluster/*"
```

For task definitions, you can specify the latest revision, or a specific revision.

To specify all revisions of the task definition, use the wildcard (\$1):

```
"Resource:arn:${Partition}:ecs:${Region}:${Account}:task-definition/${TaskDefinitionFamilyName}:*"
```

To specify a specific task definition revision, use \$1\$1TaskDefinitionRevisionNumber\$1:

```
"Resource:arn:${Partition}:ecs:${Region}:${Account}:task-definition/${TaskDefinitionFamilyName}:${TaskDefinitionRevisionNumber}"
```

To view examples of Amazon ECS identity-based policies, see [Identity-based policy examples for Amazon Elastic Container Service](security_iam_id-based-policy-examples.md).

## Policy condition keys for Amazon ECS
Policy condition keys

**Supports service-specific policy condition keys:** Yes

Administrators can use AWS JSON policies to specify who has access to what. That is, which **principal** can perform **actions** on what **resources**, and under what **conditions**.

The `Condition` element specifies when statements execute based on defined criteria. You can create conditional expressions that use [condition operators](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_condition_operators.html), such as equals or less than, to match the condition in the policy with values in the request. To see all AWS global condition keys, see [AWS global condition context keys](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_condition-keys.html) in the *IAM User Guide*.

Amazon ECS supports the following service-specific condition keys that you can use to provide fine-grained filtering for your IAM policies:


|  Condition Key  |  Description  |  Evaluation Types  | 
| --- | --- | --- | 
|  aws:RequestTag/\$1\$1TagKey\$1  |  The context key is formatted `"aws:RequestTag/tag-key":"tag-value"` where *tag-key*and *tag-value* are a tag key and value pair. Checks that the tag key–value pair is present in an AWS request. For example, you could check to see that the request includes the tag key `"Dept"` and that it has the value `"Accounting"`.  |  String  | 
|  aws:ResourceTag/\$1\$1TagKey\$1  |  The context key is formatted `"aws:ResourceTag/tag-key":"tag-value"` where *tag-key*and *tag-value* are a tag key and value pair. Checks that the tag attached to the identity resource (user or role) matches the specified key name and value.  |  String  | 
|  aws:TagKeys  |  This context key is formatted `"aws:TagKeys":"tag-key"` where *tag-key* is a list of tag keys without values (for example, `["Dept","Cost-Center"]`). Checks the tag keys that are present in an AWS request.  |  String  | 
|  ecs:ResourceTag/\$1\$1TagKey\$1  |  The context key is formatted `"ecs:ResourceTag/tag-key":"tag-value"` where *tag-key*and *tag-value* are a tag key and value pair. Checks that the tag attached to the identity resource (user or role) matches the specified key name and value.  |  String  | 
| ecs:account-setting |  he context key is formatted `"ecs:account-setting":"account-setting"` where *account-setting* is the name of the account setting.  | String | 
| ecs:auto-assign-public-ip | The context key is formatted "ecs:auto-assign-public-ip":"value" where value- is "true" or "false". | String | 
|  ecs:capacity-provider  |  The context key is formatted `"ecs:capacity-provider":"capacity-provider-arn"` where *capacity-provider-arn* is the ARN for the capacity provider.  |  ARN, Null  | 
|  ecs:cluster  |  The context key is formatted `"ecs:cluster":"cluster-arn"` where *cluster-arn* is the ARN for the Amazon ECS cluster.  |  ARN, Null  | 
|  ecs:compute-compatability  | The context key is formatted "ecs:compute-compatability":"compatability-type" where  compatability-type  is "FARGATE", "EC2" or "EXTERNAL". | String | 
|  ecs:container-instances  |  The context key is formatted `"ecs:container-instances":"container-instance-arns"` where *container-instance-arns* is one or more container instance ARNs.  |  ARN, Null  | 
| ecs:container-name |  The context key is formatted `"ecs:container-name":"container-name"` where *container-instance-* is the name of an Amazon ECS container which is defined in the task definition.   | String | 
| ecs:enable-execute-command | The context key is formatted "ecs:enable-execute-command":"value" where value- is "true" or "false". | String | 
|  ecs:enable-service-connect  |  The context key is formatted `"ecs:enable-service-connect":"value"` where *value* is `"true"` or `"false"`.  |  String  | 
|  ecs:enable-ebs-volumes  |  The context key is formatted `"ecs:enable-ebs-volumes":"value"` where *value* is `"true"` or `"false"`.  |  String  | 
| ecs:enable-managed-tags |  The context key is formatted `"ecs:enable-managed-tags":"value"` where *value* is `"true"` or `"false"`.  | String | 
| ecs:enable-vpc-lattice |  The context key is formatted `"ecs:vpc-lattice":"value"` where *value* is `"true"` or `"false"`.  | String | 
| ecs:fargate-ephemeral-storage-kms-key |  The context key is formatted `"ecs:fargate-ephemeral-storage-kms-key":"key"` where *key* is the ID of the AWS KMS key.  | String | 
|  ecs:namespace  |  The context key is formatted `"ecs:namespace":"namespace-arn"` where *namespace-arn* is the ARN for the AWS Cloud Map namespace.  |  ARN, Null  | 
| ecs:propagate-tags |  The context key is formatted `"ecs:propagate-tags":"value"` where *value* is `"TASK_DEFINITION"`, `"SERVICE"`, or `"NONE"`.  | String | 
|  ecs:service  |  The context key is formatted `"ecs:service":"service-arn"` where *service-arn* is the ARN for the Amazon ECS service.  |  ARN, Null  | 
|  ecs:task-definition  |  The context key is formatted `"ecs:task-definition":"task-definition-arn"` where *task-definition-arn* is the ARN for the Amazon ECS task definition.  |  ARN, Null  | 
| ecs:subnet |  The context key is formatted `"ecs:subnet":"subnets"` where *subnets* are the subnets of a task or service that uses `awsvpc` mode.  | String | 
|  ecs:task  |  The context key is formatted `"ecs:task":"task-arn"` where *task-arn* is the ARN for the Amazon ECS service.  |  ARN, Null  | 
| ecs:task-cpu | The context key is formatted "ecs:task-cpu":"task-cpu" where task-cpu is the task cpu, as an integer with 1024 = 1 vCPU. | Integer | 
| ecs:task-memory | The context key is formatted "ecs:task-memory":"task-memory" where task-memory is the task memory in MiB. | Integer | 

To see a list of Amazon ECS condition keys, see [Condition keys for Amazon Elastic Container Service](https://docs.aws.amazon.com/service-authorization/latest/reference/list_amazonelasticcontainerservice.html#amazonelasticcontainerservice-policy-keys) in the *Service Authorization Reference*. To learn with which actions and resources you can use a condition key, see [Actions defined by Amazon Elastic Container Service](https://docs.aws.amazon.com/service-authorization/latest/reference/list_amazonelasticcontainerservice.html#amazonelasticcontainerservice-actions-as-permissions).

To view examples of Amazon ECS identity-based policies, see [Identity-based policy examples for Amazon Elastic Container Service](security_iam_id-based-policy-examples.md).

## Access control lists (ACLs) in Amazon ECS
ACLs

**Supports ACLs:** No 

Access control lists (ACLs) control which principals (account members, users, or roles) have permissions to access a resource. ACLs are similar to resource-based policies, although they do not use the JSON policy document format.

## Attribute-based access control (ABAC) with Amazon ECS
ABAC

**Important**  
Amazon ECS supports attributes-based access control for all Amazon ECS resources. To determine whether you can use attributes to scope an action, use the [Actions defined by Amazon ECS](https://docs.aws.amazon.com/service-authorization/latest/reference/list_amazonelasticcontainerservice.html#amazonelasticcontainerservice-actions-as-permissions) table in *Service Authorization Reference*. First verify that there is a resource in the **Resource** column. Then, use the **Condition keys** column to see the keys for the action/resource combination.

**Supports ABAC (tags in policies):** Yes

Attribute-based access control (ABAC) is an authorization strategy that defines permissions based on attributes called tags. You can attach tags to IAM entities and AWS resources, then design ABAC policies to allow operations when the principal's tag matches the tag on the resource.

To control access based on tags, you provide tag information in the [condition element](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_condition.html) of a policy using the `aws:ResourceTag/key-name`, `aws:RequestTag/key-name`, or `aws:TagKeys` condition keys.

If a service supports all three condition keys for every resource type, then the value is **Yes** for the service. If a service supports all three condition keys for only some resource types, then the value is **Partial**.

For more information about ABAC, see [Define permissions with ABAC authorization](https://docs.aws.amazon.com/IAM/latest/UserGuide/introduction_attribute-based-access-control.html) in the *IAM User Guide*. To view a tutorial with steps for setting up ABAC, see [Use attribute-based access control (ABAC)](https://docs.aws.amazon.com/IAM/latest/UserGuide/tutorial_attribute-based-access-control.html) in the *IAM User Guide*.

For more information about tagging Amazon ECS resources, see [Tagging Amazon ECS resources](ecs-using-tags.md).

To view an example identity-based policy for limiting access to a resource based on the tags on that resource, see [Describing Amazon ECS services based on tags](security_iam_id-based-policy-examples.md#security_iam_id-based-policy-examples-view-cluster-tags).

## Using Temporary credentials with Amazon ECS
Temporary credentials

**Supports temporary credentials:** Yes

Temporary credentials provide short-term access to AWS resources and are automatically created when you use federation or switch roles. AWS recommends that you dynamically generate temporary credentials instead of using long-term access keys. For more information, see [Temporary security credentials in IAM](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_temp.html) and [AWS services that work with IAM](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_aws-services-that-work-with-iam.html) in the *IAM User Guide*.

## Forward access sessions for Amazon ECS
Principal permissions

**Supports forward access sessions (FAS):** Yes

 Forward access sessions (FAS) use the permissions of the principal calling an AWS service, combined with the requesting AWS service to make requests to downstream services. For policy details when making FAS requests, see [Forward access sessions](https://docs.aws.amazon.com/IAM/latest/UserGuide/access_forward_access_sessions.html). 

## Service roles for Amazon ECS
Service roles

**Supports service roles:** Yes

 A service role is an [IAM role](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles.html) that a service assumes to perform actions on your behalf. An IAM administrator can create, modify, and delete a service role from within IAM. For more information, see [Create a role to delegate permissions to an AWS service](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_create_for-service.html) in the *IAM User Guide*. 

**Warning**  
Changing the permissions for a service role might break Amazon ECS functionality. Edit service roles only when Amazon ECS provides guidance to do so.

## Service-linked roles for Amazon ECS
Service-linked roles

**Supports service-linked roles:** Yes

 A service-linked role is a type of service role that is linked to an AWS service. The service can assume the role to perform an action on your behalf. Service-linked roles appear in your AWS account and are owned by the service. An IAM administrator can view, but not edit the permissions for service-linked roles. 

For details about creating or managing Amazon ECS service-linked roles, see [Using service-linked roles for Amazon ECS](using-service-linked-roles.md).

# Identity-based policy examples for Amazon Elastic Container Service
Identity-based policy examples

By default, users and roles don't have permission to create or modify Amazon ECS resources. To grant users permission to perform actions on the resources that they need, an IAM administrator can create IAM policies.

To learn how to create an IAM identity-based policy by using these example JSON policy documents, see [Create IAM policies (console)](https://docs.aws.amazon.com/IAM/latest/UserGuide/access_policies_create-console.html) in the *IAM User Guide*.

For details about actions and resource types defined by Amazon ECS, including the format of the ARNs for each of the resource types, see [Actions, resources, and condition keys for Amazon Elastic Container Service](https://docs.aws.amazon.com/service-authorization/latest/reference/list_amazonelasticcontainerservice.html) in the *Service Authorization Reference*.

**Topics**
+ [

## Amazon ECS policy best practices
](#security_iam_service-with-iam-policy-best-practices)
+ [

## Allow Amazon ECS users to view their own permissions
](#security_iam_id-based-policy-examples-view-own-permissions)
+ [

## Amazon ECS cluster examples
](#IAM_cluster_policies)
+ [

## Amazon ECS container instance examples
](#IAM_container_instance_policies)
+ [

## Amazon ECS task definition examples
](#IAM_task_definition_policies)
+ [

## Run Amazon ECS Task Example
](#IAM_run_policies)
+ [

## Start Amazon ECS task example
](#IAM_start_policies)
+ [

## List and describe Amazon ECS task examples
](#IAM_task_policies)
+ [

## Create Amazon ECS service example
](#IAM_create_service_policies)
+ [

## Describing Amazon ECS services based on tags
](#security_iam_id-based-policy-examples-view-cluster-tags)
+ [

## Deny Amazon ECS Service Connect Namespace Override Example
](#IAM_disable_namespace_override_policies)

## Amazon ECS policy best practices


Identity-based policies determine whether someone can create, access, or delete Amazon ECS resources in your account. These actions can incur costs for your AWS account. When you create or edit identity-based policies, follow these guidelines and recommendations:
+ **Get started with AWS managed policies and move toward least-privilege permissions** – To get started granting permissions to your users and workloads, use the *AWS managed policies* that grant permissions for many common use cases. They are available in your AWS account. We recommend that you reduce permissions further by defining AWS customer managed policies that are specific to your use cases. For more information, see [AWS managed policies](https://docs.aws.amazon.com/IAM/latest/UserGuide/access_policies_managed-vs-inline.html#aws-managed-policies) or [AWS managed policies for job functions](https://docs.aws.amazon.com/IAM/latest/UserGuide/access_policies_job-functions.html) in the *IAM User Guide*.
+ **Apply least-privilege permissions** – When you set permissions with IAM policies, grant only the permissions required to perform a task. You do this by defining the actions that can be taken on specific resources under specific conditions, also known as *least-privilege permissions*. For more information about using IAM to apply permissions, see [ Policies and permissions in IAM](https://docs.aws.amazon.com/IAM/latest/UserGuide/access_policies.html) in the *IAM User Guide*.
+ **Use conditions in IAM policies to further restrict access** – You can add a condition to your policies to limit access to actions and resources. For example, you can write a policy condition to specify that all requests must be sent using SSL. You can also use conditions to grant access to service actions if they are used through a specific AWS service, such as CloudFormation. For more information, see [ IAM JSON policy elements: Condition](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_condition.html) in the *IAM User Guide*.
+ **Use IAM Access Analyzer to validate your IAM policies to ensure secure and functional permissions** – IAM Access Analyzer validates new and existing policies so that the policies adhere to the IAM policy language (JSON) and IAM best practices. IAM Access Analyzer provides more than 100 policy checks and actionable recommendations to help you author secure and functional policies. For more information, see [Validate policies with IAM Access Analyzer](https://docs.aws.amazon.com/IAM/latest/UserGuide/access-analyzer-policy-validation.html) in the *IAM User Guide*.
+ **Require multi-factor authentication (MFA)** – If you have a scenario that requires IAM users or a root user in your AWS account, turn on MFA for additional security. To require MFA when API operations are called, add MFA conditions to your policies. For more information, see [ Secure API access with MFA](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_mfa_configure-api-require.html) in the *IAM User Guide*.

For more information about best practices in IAM, see [Security best practices in IAM](https://docs.aws.amazon.com/IAM/latest/UserGuide/best-practices.html) in the *IAM User Guide*.

## Allow Amazon ECS users to view their own permissions


This example shows how you might create a policy that allows IAM users to view the inline and managed policies that are attached to their user identity. This policy includes permissions to complete this action on the console or programmatically using the AWS CLI or AWS API.

```
{
    "Version": "2012-10-17",		 	 	 
    "Statement": [
        {
            "Sid": "ViewOwnUserInfo",
            "Effect": "Allow",
            "Action": [
                "iam:GetUserPolicy",
                "iam:ListGroupsForUser",
                "iam:ListAttachedUserPolicies",
                "iam:ListUserPolicies",
                "iam:GetUser"
            ],
            "Resource": ["arn:aws:iam::*:user/${aws:username}"]
        },
        {
            "Sid": "NavigateInConsole",
            "Effect": "Allow",
            "Action": [
                "iam:GetGroupPolicy",
                "iam:GetPolicyVersion",
                "iam:GetPolicy",
                "iam:ListAttachedGroupPolicies",
                "iam:ListGroupPolicies",
                "iam:ListPolicyVersions",
                "iam:ListPolicies",
                "iam:ListUsers"
            ],
            "Resource": "*"
        }
    ]
}
```

## Amazon ECS cluster examples


The following IAM policy allows permission to create and list clusters. The `CreateCluster` and `ListClusters` actions do not accept any resources, so the resource definition is set to `*` for all resources.

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

****  

```
{
    "Statement": [
        {
            "Effect": "Allow",
            "Action": [
                "ecs:CreateCluster",
                "ecs:ListClusters"
            ],
            "Resource": "*"
        }
    ]
}
```

------

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

****  

```
{
    "Statement": [
        {
            "Effect": "Allow",
            "Action": [
                "ecs:DescribeClusters",
                "ecs:DeleteCluster"
            ],
            "Resource": ["arn:aws:ecs:us-east-1:123456789012:cluster/cluster-name"]
        }
    ]
}
```

------

The following IAM policy allows permission to describe and delete a specific cluster. The `DescribeClusters` and `DeleteCluster` actions accept cluster ARNs as resources.

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

****  

```
{
    "Statement": [
        {
            "Action": [
                "ecs:Describe*",
                "ecs:List*"
            ],
            "Effect": "Allow",
            "Resource": "*"
        },
        {
            "Action": [
                "ecs:DeleteCluster",
                "ecs:DeregisterContainerInstance",
                "ecs:ListContainerInstances",
                "ecs:RegisterContainerInstance",
                "ecs:SubmitContainerStateChange",
                "ecs:SubmitTaskStateChange"
            ],
            "Effect": "Allow",
            "Resource": "arn:aws:ecs:us-east-1:123456789012:cluster/default"
        },
        {
            "Action": [
                "ecs:DescribeContainerInstances",
                "ecs:DescribeTasks",
                "ecs:ListTasks",
                "ecs:UpdateContainerAgent",
                "ecs:StartTask",
                "ecs:StopTask",
                "ecs:RunTask"
            ],
            "Effect": "Allow",
            "Resource": "*",
            "Condition": {
                "ArnEquals": {"ecs:cluster": "arn:aws:ecs:us-east-1:123456789012:cluster/default"}
            }
        }
    ]
}
```

------

The following IAM policy can be attached to a user or group that would only allow that user or group to perform operations on a specific cluster.

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

****  

```
{
    "Version":"2012-10-17",		 	 	 
    "Statement": [
        {
            "Action": [
                "ecs:Describe*",
                "ecs:List*"
            ],
            "Effect": "Allow",
            "Resource": "*"
        },
        {
            "Action": [
                "ecs:DeleteCluster",
                "ecs:DeregisterContainerInstance",
                "ecs:ListContainerInstances",
                "ecs:RegisterContainerInstance",
                "ecs:SubmitContainerStateChange",
                "ecs:SubmitTaskStateChange"
            ],
            "Effect": "Allow",
            "Resource": "arn:aws:ecs:us-east-1:111122223333:cluster/default"
        },
        {
            "Action": [
                "ecs:DescribeContainerInstances",
                "ecs:DescribeTasks",
                "ecs:ListTasks",
                "ecs:UpdateContainerAgent",
                "ecs:StartTask",
                "ecs:StopTask",
                "ecs:RunTask"
            ],
            "Effect": "Allow",
            "Resource": "*",
            "Condition": {
                "ArnEquals": {"ecs:cluster": "arn:aws:ecs:us-east-1:111122223333:cluster/default"}
            }
        }
    ]
}
```

------

## Amazon ECS container instance examples


Container instance registration is handled by the Amazon ECS agent, but there may be times where you want to allow a user to deregister an instance manually from a cluster. Perhaps the container instance was accidentally registered to the wrong cluster, or the instance was terminated with tasks still running on it.

The following IAM policy allows a user to list and deregister container instances in a specified cluster:

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

****  

```
{
    "Statement": [
        {
            "Effect": "Allow",
            "Action": [
                "ecs:DeregisterContainerInstance",
                "ecs:ListContainerInstances"
            ],
            "Resource": "arn:aws:ecs:us-east-1:123456789012:cluster/cluster_name"
        }
    ]
}
```

------

## Amazon ECS task definition examples


Task definition IAM policies do not support resource-level permissions, but the following IAM policy allows a user to register, list, and describe task definitions:

If you use the console, you must add `CloudFormation: CreateStack` as an `Action`.

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

****  

```
{
    "Statement": [
        {
            "Effect": "Allow",
            "Action": [
                "ecs:RegisterTaskDefinition",
                "ecs:ListTaskDefinitions",
                "ecs:DescribeTaskDefinition"
            ],
            "Resource": "*"
        }
    ]
}
```

------

## Run Amazon ECS Task Example


The resources for `RunTask` are task definitions. To limit which clusters a user can run task definitions on, you can specify them in the `Condition` block. The advantage is that you don't have to list both task definitions and clusters in your resources to allow the appropriate access. You can apply one, the other, or both.

The following IAM policy allows permission to run any revision of a specific task definition on a specific cluster:

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

****  

```
{
    "Statement": [
        {
            "Effect": "Allow",
            "Action": ["ecs:RunTask"],
            "Condition": {
                "ArnEquals": {"ecs:cluster": "arn:aws:ecs:us-east-1:123456789012:cluster/cluster_name"}
            },
            "Resource": ["arn:aws:ecs:us-east-1:123456789012:task-definition/task_family:*"]
        }
    ]
}
```

------

## Start Amazon ECS task example


The resources for `StartTask` are task definitions. To limit which clusters and container instances a user can start task definitions on, you can specify them in the `Condition` block. The advantage is that you don't have to list both task definitions and clusters in your resources to allow the appropriate access. You can apply one, the other, or both.

The following IAM policy allows permission to start any revision of a specific task definition on a specific cluster and specific container instance.

**Note**  
For this example, when you call the `StartTask` API with the AWS CLI or another AWS SDK, you must specify the task definition revision so that the `Resource` mapping matches.

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

****  

```
{
    "Statement": [
        {
            "Effect": "Allow",
            "Action": ["ecs:StartTask"],
            "Condition": {
                "ArnEquals": {
                    "ecs:cluster": "arn:aws:ecs:us-east-1:123456789012:cluster/cluster_name",
                    "ecs:container-instances": ["arn:aws:ecs:us-east-1:123456789012:container-instance/cluster_name/container_instance_UUID"]
                }
            },
            "Resource": ["arn:aws:ecs:us-east-1:123456789012:task-definition/task_family:*"]
        }
    ]
}
```

------

## List and describe Amazon ECS task examples


The following IAM policy allows a user to describe a specified task in a specified cluster:

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

****  

```
{
    "Statement": [
        {
            "Effect": "Allow",
            "Action": ["ecs:DescribeTasks"],
            "Condition": {
                "ArnEquals": {"ecs:cluster": "arn:aws:ecs:us-east-1:123456789012:cluster/cluster_name"}
            },
            "Resource": ["arn:aws:ecs:us-east-1:123456789012:task/cluster_name/task_UUID"]
        }
    ]
}
```

------

## Create Amazon ECS service example


The following IAM policy allows a user to create Amazon ECS services in the AWS Management Console:

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

****  

```
{
    "Version":"2012-10-17",		 	 	 
    "Statement": [
        {
            "Effect": "Allow",
            "Action": [
                "application-autoscaling:Describe*",
                "application-autoscaling:PutScalingPolicy",
                "application-autoscaling:RegisterScalableTarget",
                "cloudwatch:DescribeAlarms",
                "cloudwatch:PutMetricAlarm",
                "ecs:List*",
                "ecs:Describe*",
                "ecs:CreateService",
                "elasticloadbalancing:Describe*",
                "iam:GetPolicy",
                "iam:GetPolicyVersion",
                "iam:GetRole",
                "iam:ListAttachedRolePolicies",
                "iam:ListRoles",
                "iam:ListGroups",
                "iam:ListUsers"
            ],
            "Resource": "*"
        }
    ]
}
```

------

## Describing Amazon ECS services based on tags


You can use conditions in your identity-based policy to control access to Amazon ECS resources based on tags. This example shows how you might create a policy that allows describing your services. However, permission is granted only if the service tag `Owner` has the value of that user's user name. This policy also grants the permissions necessary to complete this action on the console.

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

****  

```
{
    "Version":"2012-10-17",		 	 	 
    "Statement": [
        {
            "Sid": "DescribeServices",
            "Effect": "Allow",
            "Action": "ecs:DescribeServices",
            "Resource": "*"
        },
        {
            "Sid": "ViewServiceIfOwner",
            "Effect": "Allow",
            "Action": "ecs:DescribeServices",
            "Resource": "arn:aws:ecs:*:*:service/*",
            "Condition": {
                "StringEquals": {"ecs:ResourceTag/Owner": "${aws:username}"}
            }
        }
    ]
}
```

------

You can attach this policy to the IAM users in your account. If a user named `richard-roe` attempts to describe an Amazon ECS service, the service must be tagged `Owner=richard-roe` or `owner=richard-roe`. Otherwise he is denied access. The condition tag key `Owner` matches both `Owner` and `owner` because condition key names are not case-sensitive. For more information, see [IAM JSON Policy Elements: Condition](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_condition.html) in the *IAM User Guide*.

## Deny Amazon ECS Service Connect Namespace Override Example


The following IAM policy denies a user from overriding the default Service Connect namespace in a service configuration. The default namespace is set in the cluster. However, you can override it in a service configuration. For consistency, consider setting all your new services to use the same namespace. Use the following context keys to require services to use a specific namespace. Replace the `<region>`, `<aws_account_id>`, `<cluster_name>` and `<namespace_id>` with your own in the following example.

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

****  

```
{
    "Version":"2012-10-17",		 	 	 
    "Statement": [
        {
            "Effect": "Allow",
            "Action": [
                "ecs:CreateService",
                "ecs:UpdateService"
            ],
            "Condition": {
                "ArnEquals": {
                    "ecs:cluster": "arn:aws:ecs:us-east-1:123456789012:cluster/cluster_name",
                    "ecs:namespace": "arn:aws:servicediscovery:us-east-1:123456789012:namespace/namespace_id"
                }
            },
            "Resource": "*"
        }
    ]
}
```

------

 

 

 

# AWS managed policies for Amazon Elastic Container Service
AWS managed policies for Amazon ECS

To add permissions to users, groups, and roles, it is easier to use AWS managed policies than to write policies yourself. It takes time and expertise to [create IAM customer managed policies](https://docs.aws.amazon.com/IAM/latest/UserGuide/access_policies_create-console.html) that provide your team with only the permissions they need. To get started quickly, you can use our AWS managed policies. These policies cover common use cases and are available in your AWS account. For more information about AWS managed policies, see [AWS managed policies](https://docs.aws.amazon.com/IAM/latest/UserGuide/access_policies_managed-vs-inline.html#aws-managed-policies) in the *IAM User Guide*.

AWS services maintain and update AWS managed policies. You can't change the permissions in AWS managed policies. Services occasionally add additional permissions to an AWS managed policy to support new features. This type of update affects all identities (users, groups, and roles) where the policy is attached. Services are most likely to update an AWS managed policy when a new feature is launched or when new operations become available. Services do not remove permissions from an AWS managed policy, so policy updates won't break your existing permissions.

Additionally, AWS supports managed policies for job functions that span multiple services. For example, the **ReadOnlyAccess** AWS managed policy provides read-only access to all AWS services and resources. When a service launches a new feature, AWS adds read-only permissions for new operations and resources. For a list and descriptions of job function policies, see [AWS managed policies for job functions](https://docs.aws.amazon.com/IAM/latest/UserGuide/access_policies_job-functions.html) in the *IAM User Guide*.

Amazon ECS and Amazon ECR provide several managed policies and trust relationships that you can attach to users, groups, roles, Amazon EC2 instances, and Amazon ECS tasks that allow differing levels of control over resources and API operations. You can apply these policies directly, or you can use them as starting points for creating your own policies. For more information about the Amazon ECR managed policies, see [Amazon ECR managed policies](https://docs.aws.amazon.com/AmazonECR/latest/userguide/ecr_managed_policies.html).

## AmazonECS\$1FullAccess
AmazonECS\$1FullAccess

You can attach the `AmazonECS_FullAccess` policy to your IAM identities. This policy grants administrative access to Amazon ECS resources and grants an IAM identity (such as a user, group, or role) access to the AWS services that Amazon ECS is integrated with to use all of Amazon ECS features. Using this policy allows access to all of Amazon ECS features that are available in the AWS Management Console.

To view the permissions for this policy, see [AmazonECS\$1FullAccess](https://docs.aws.amazon.com/aws-managed-policy/latest/reference/AmazonECS_FullAccess.html) in the *AWS Managed Policy Reference*.

## AmazonECSInfrastructureRolePolicyForVolumes


You can attach the `AmazonECSInfrastructureRolePolicyForVolumes` managed policy to your IAM entities.

The policy grants the permissions that are needed by Amazon ECS to make AWS API calls on your behalf. You can attach this policy to the IAM role that you provide with your volume configuration when you launch Amazon ECS tasks and services. The role allows Amazon ECS to manage volumes attached to your tasks. For more information, see [Amazon ECS infrastructure IAM role](https://docs.aws.amazon.com/AmazonECS/latest/developerguide/infrastructure_IAM_role.html).

To view the permissions for this policy, see [AmazonECSInfrastructureRolePolicyForVolumes](https://docs.aws.amazon.com/aws-managed-policy/latest/reference/AmazonECSInfrastructureRolePolicyForVolumes.html) in the *AWS Managed Policy Reference*.

## AmazonEC2ContainerServiceforEC2Role


You can attach the `AmazonEC2ContainerServiceforEC2Role` policy to your IAM identities. This policy grants administrative permissions that allow Amazon ECS container instances to make calls to AWS on your behalf. For more information, see [Amazon ECS container instance IAM role](instance_IAM_role.md).

Amazon ECS attaches this policy to a service role that allows Amazon ECS to perform actions on your behalf against Amazon EC2 instances or external instances.

To view the permissions for this policy, see [AmazonEC2ContainerServiceforEC2Role](https://docs.aws.amazon.com/aws-managed-policy/latest/reference/AmazonEC2ContainerServiceforEC2Role.html) in the *AWS Managed Policy Reference*.

### Considerations


You should consider the following recommendations and considerations when using the `AmazonEC2ContainerServiceforEC2Role` managed IAM policy.
+ Following the standard security advice of granting least privilege, you can modify the `AmazonEC2ContainerServiceforEC2Role` managed policy to fit your specific needs. If any of the permissions granted in the managed policy aren't needed for your use case, create a custom policy and add only the permissions that you require. For example, the `UpdateContainerInstancesState` permission is provided for Spot Instance draining. If that permission isn't needed for your use case, exclude it using a custom policy. 
+ Containers that are running on your container instances have access to all of the permissions that are supplied to the container instance role through [instance metadata](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-instance-metadata.html). We recommend that you limit the permissions in your container instance role to the minimal list of permissions that are provided in the managed `AmazonEC2ContainerServiceforEC2Role` policy. If the containers in your tasks need extra permissions that aren't listed, we recommend providing those tasks with their own IAM roles. For more information, see [Amazon ECS task IAM role](task-iam-roles.md).

  You can prevent containers on the `docker0` bridge from accessing the permissions supplied to the container instance role. You can do this while still allowing the permissions that are provided by [Amazon ECS task IAM role](task-iam-roles.md) by running the following **iptables** command on your container instances. Containers can't query instance metadata with this rule in effect. This command assumes the default Docker bridge configuration and it doesn't work with containers that use the `host` network mode. For more information, see [Network mode](task_definition_parameters.md#network_mode).

  ```
  sudo yum install -y iptables-services; sudo iptables --insert DOCKER USER 1 --in-interface docker+ --destination 169.254.169.254/32 --jump DROP
  ```

  You must save this **iptables** rule on your container instance for it to survive a reboot. For the Amazon ECS-optimized AMI, use the following command. For other operating systems, consult the documentation for that OS.
  + For the Amazon ECS-optimized Amazon Linux 2 AMI:

    ```
    sudo iptables-save | sudo tee /etc/sysconfig/iptables && sudo systemctl enable --now iptables
    ```
  + For the Amazon ECS-optimized Amazon Linux AMI:

    ```
    sudo service iptables save
    ```

## AmazonEC2ContainerServiceEventsRole


You can attach the `AmazonEC2ContainerServiceEventsRole` policy to your IAM identities. This policy grants permissions that allow Amazon EventBridge (formerly CloudWatch Events) to run tasks on your behalf. This policy can be attached to the IAM role that's specified when you create scheduled tasks. For more information, see [Amazon ECS EventBridge IAM Role](CWE_IAM_role.md).

To view the permissions for this policy, see [AmazonEC2ContainerServiceEventsRole](https://docs.aws.amazon.com/aws-managed-policy/latest/reference/AmazonEC2ContainerServiceEventsRole.html) in the *AWS Managed Policy Reference*.

## AmazonECSTaskExecutionRolePolicy


The `AmazonECSTaskExecutionRolePolicy` managed IAM policy grants the permissions that are needed by the Amazon ECS container agent and AWS Fargate container agents to make AWS API calls on your behalf. This policy can be added to your task execution IAM role. For more information, see [Amazon ECS task execution IAM role](task_execution_IAM_role.md).

To view the permissions for this policy, see [AmazonECSTaskExecutionRolePolicy](https://docs.aws.amazon.com/aws-managed-policy/latest/reference/AmazonECSTaskExecutionRolePolicy.html) in the *AWS Managed Policy Reference*.

## AmazonECSServiceRolePolicy


The `AmazonECSServiceRolePolicy` managed IAM policy enables Amazon Elastic Container Service to manage your cluster. This policy can be added to your [AWSServiceRoleForECS](https://docs.aws.amazon.com/AmazonECS/latest/developerguide/using-service-linked-roles-for-clusters.html#service-linked-role-permissions-clusters) service-linked role. 

To view the permissions for this policy, see [AmazonECSServiceRolePolicy](https://docs.aws.amazon.com/aws-managed-policy/latest/reference/AmazonECSServiceRolePolicy.html) in the *AWS Managed Policy Reference*.

## `AmazonECSInfrastructureRolePolicyForServiceConnectTransportLayerSecurity`


You can attach the `AmazonECSInfrastructureRolePolicyForServiceConnectTransportLayerSecurity` policy to your IAM entities. This policy grants administrative access to AWS Private Certificate Authority, Secrets Manager and other AWS Services required to manage Amazon ECS Service Connect TLS features on your behalf.

To view the permissions for this policy, see [AmazonECSInfrastructureRolePolicyForServiceConnectTransportLayerSecurity](https://docs.aws.amazon.com/aws-managed-policy/latest/reference/AmazonECSInfrastructureRolePolicyForServiceConnectTransportLayerSecurity.html) in the *AWS Managed Policy Reference*.

## `AWSApplicationAutoscalingECSServicePolicy`


You can't attach `AWSApplicationAutoscalingECSServicePolicy` to your IAM entities. This policy is attached to a service-linked role that allows Application Auto Scaling to perform actions on your behalf. For more information, see [Service-linked roles for Application Auto Scaling](https://docs.aws.amazon.com/autoscaling/application/userguide/application-auto-scaling-service-linked-roles.html).

To view the permissions for this policy, see [AWSApplicationAutoscalingECSServicePolicy](https://docs.aws.amazon.com/aws-managed-policy/latest/reference/AWSApplicationAutoscalingECSServicePolicy.html) in the *AWS Managed Policy Reference*.

## `AWSCodeDeployRoleForECS`


You can't attach `AWSCodeDeployRoleForECS` to your IAM entities. This policy is attached to a service-linked role that allows CodeDeploy to perform actions on your behalf. For more information, see [Create a service role for CodeDeploy](https://docs.aws.amazon.com/codedeploy/latest/userguide/getting-started-create-service-role.html) in the *AWS CodeDeploy User Guide*.

To view the permissions for this policy, see [AWSCodeDeployRoleForECS](https://docs.aws.amazon.com/aws-managed-policy/latest/reference/AWSCodeDeployRoleForECS.html) in the *AWS Managed Policy Reference*.

## `AWSCodeDeployRoleForECSLimited`


You can't attach `AWSCodeDeployRoleForECSLimited` to your IAM entities. This policy is attached to a service-linked role that allows CodeDeploy to perform actions on your behalf. For more information, see [Create a service role for CodeDeploy](https://docs.aws.amazon.com/codedeploy/latest/userguide/getting-started-create-service-role.html) in the *AWS CodeDeploy User Guide*.

To view the permissions for this policy, see [AWSCodeDeployRoleForECSLimited](https://docs.aws.amazon.com/aws-managed-policy/latest/reference/AWSCodeDeployRoleForECSLimited.html) in the *AWS Managed Policy Reference*.

## `AmazonECSInfrastructureRolePolicyForLoadBalancers`


You can attach the `AmazonECSInfrastructureRolePolicyForLoadBalancers` policy to your IAM entities. This policy grants permissions that allow Amazon ECS to manage Elastic Load Balancing resources on your behalf. The policy includes:
+ Read-only permissions to describe listeners, rules, target groups, and target health
+ Permissions to register and deregister targets with target groups
+ Permissions to modify listeners for Application Load Balancers and Network Load Balancers
+ Permissions to modify rules for Application Load Balancers

These permissions enable Amazon ECS to automatically manage load balancer configurations when services are created or updated, ensuring proper routing of traffic to your containers.

To view the permissions for this policy, see [AmazonECSInfrastructureRolePolicyForLoadBalancers](https://docs.aws.amazon.com/aws-managed-policy/latest/reference/AmazonECSInfrastructureRolePolicyForLoadBalancers.html) in the *AWS Managed Policy Reference*.

## `AmazonECSInfrastructureRolePolicyForManagedInstances`


You can attach the `AmazonECSInfrastructureRolePolicyForManagedInstances` policy to your IAM entities. This policy grants the permissions required by Amazon ECS to create and update Amazon EC2 resources for ECS Managed Instances on your behalf. The policy includes:
+ Permissions to create and manage Amazon EC2 launch templates for managed instances
+ Permissions to provision Amazon EC2 instances using CreateFleet and RunInstances
+ Permissions to create and manage tags on Amazon EC2 resources created by ECS
+ Permissions to pass IAM roles to Amazon EC2 instances for managed instances
+ Permissions to create service-linked roles for Amazon EC2 Spot instances
+ Read-only permissions to describe Amazon EC2 resources including instances, instance types, launch templates, network interfaces, availability zones, security groups, subnets, VPCs, EC2 Images and capacity reservations
+ Read-only permissions to list Amazon ResourceGroups resources, which requires underlying permissions to get tagged resources and list Amazon CloudFormation stack resources

These permissions enable Amazon ECS to automatically provision and manage Amazon EC2 instances for your ECS Managed Instances, ensuring proper configuration and lifecycle management of the underlying compute resources.

To view the permissions for this policy, see [AmazonECSInfrastructureRolePolicyForManagedInstances](https://docs.aws.amazon.com/aws-managed-policy/latest/reference/AmazonECSInfrastructureRolePolicyForManagedInstances.html) in the *AWS Managed Policy Reference*.

## `AmazonECSInfrastructureRolePolicyForVpcLattice`


You can attach the `AmazonECSInfrastructureRolePolicyForVpcLattice` policy to your IAM entities. This policy Provides access to other AWS service resources required to manage VPC Lattice feature in Amazon ECS workloads on your behalf.

To view the permissions for this policy, see [AmazonECSInfrastructureRolePolicyForVpcLattice](https://docs.aws.amazon.com/aws-managed-policy/latest/reference/AmazonECSInfrastructureRolePolicyForVpcLattice.html) in the *AWS Managed Policy Reference*.

Provides access to other AWS service resources required to manage VPC Lattice feature in Amazon ECS workloads on your behalf.

## `AmazonECSInfrastructureRoleforExpressGatewayServices`


You can attach the `AmazonECSInfrastructureRoleforExpressGatewayServices` policy to your IAM entities. This policy grants the permissions required by Amazon ECS to create and update web applications using Express Services on your behalf. The policy includes:
+ Permissions to create service-linked roles for Amazon ECS Application Auto Scaling
+ Permissions to create, modify, and delete Application Load Balancers, listeners, rules, and target groups
+ Permissions to create, modify, and delete VPC security groups for ECS-managed resources
+ Permissions to request, manage, and delete SSL/TLS certificates through ACM
+ Permissions to configure Application Auto Scaling policies and targets for Amazon ECS services
+ Permissions to create and manage CloudWatch alarms for auto scaling triggers
+ Read-only permissions to describe load balancers, VPC resources, certificates, auto scaling configurations, and CloudWatch alarms

These permissions enable Amazon ECS to automatically provision and manage the infrastructure components required for Express Services web applications, including load balancing, security groups, SSL certificates, and auto scaling configurations.

To view the permissions for this policy, see [AmazonECSInfrastructureRoleforExpressGatewayServices](https://docs.aws.amazon.com/aws-managed-policy/latest/reference/AmazonECSInfrastructureRoleforExpressGatewayServices.html) in the *AWS Managed Policy Reference*.

## `AmazonECSComputeServiceRolePolicy`


The `AmazonECSComputeServiceRolePolicy` policy is attached to the AmazonECSComputeServiceRole service-linked role. For more information, see [Using roles to manage Amazon ECS Managed Instances](using-service-linked-roles-instances.md).

This policy includes permissions that allow Amazon ECS to complete the following tasks:
+ Amazon ECS can describe and delete launch templates.
+  Amazon ECS can describe and delete launch template versions.
+ Amazon ECS can terminate instances.
+ Amazon ECS can describe the following instance data parameters:
  + Instance
  + Instance network interfaces: Amazon ECS can describe the the to manage the EC2 instance lifecycle.
  + Instance event window: Amazon ECS can describe the event window information in order to determine if the workflow can be interrupted for patching the instance.
  + Instance status: Amazon ECS can describe the instance status in order to monitor the instance health.

To view the permissions for this policy, see [ AmazonECSComputeServiceRolePolicy](https://docs.aws.amazon.com/aws-managed-policy/latest/reference/AmazonECSComputeServiceRolePolicy.html) in the *AWS Managed Policy Reference*.

## `AmazonECSInstanceRolePolicyForManagedInstances`


The `AmazonECSInstanceRolePolicyForManagedInstances` policy provides permissions for Amazon ECS managed instances to register with Amazon ECS clusters and communicate with the Amazon ECS service.

This policy includes permissions that allow Amazon ECS managed instances to complete the following tasks:
+ Register and deregister with Amazon ECS clusters.
+ Submit container instance state changes.
+ Submit task state changes.
+ Discover polling endpoints for the Amazon ECS agent.

To view the permissions for this policy, see [AmazonECSInstanceRolePolicyForManagedInstances](https://docs.aws.amazon.com/aws-managed-policy/latest/reference/AmazonECSInstanceRolePolicyForManagedInstances.html) in the *AWS Managed Policy Reference*.

## Amazon ECS updates to AWS managed policies
Policy updates

View details about updates to AWS managed policies for Amazon ECS since this service started tracking these changes. For automatic alerts about changes to this page, subscribe to the RSS feed on the Amazon ECS Document history page.

 


| Change | Description | Date | 
| --- | --- | --- | 
|   Update `AmazonECSInfrastructureRolePolicyForManagedInstances` policy   |  The `AmazonECSInfrastructureRolePolicyForManagedInstances` policy has been updated with the following permissions to support Capacity Reservations on Amazon ECS Managed Instances: [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/AmazonECS/latest/developerguide/security-iam-awsmanpol.html)  | February 24, 2026 | 
|  Add permissions to [AmazonECSServiceRolePolicy](https://docs.aws.amazon.com/AmazonECS/latest/developerguide/security-iam-awsmanpol.html#security-iam-awsmanpol-AmazonECSServiceRolePolicy).  | The AmazonECSServiceRolePolicy managed IAM policy was updated to include the ssmmessages:OpenDataChannel permission. This permission allows Amazon ECS to open data channels for ECS Exec sessions. | January 20, 2026 | 
|   Update `AmazonECSInfrastructureRolePolicyForManagedInstances` policy   |  The `AmazonECSInfrastructureRolePolicyForManagedInstances` policy has been updated to modify the `CreateFleet` permissions. The resource-based conditions for subnets, security groups and EC2 images have been removed because: [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/AmazonECS/latest/developerguide/security-iam-awsmanpol.html) This change ensures that the policy functions correctly with resources that lack the expected ECS management tags.   | December 15, 2025 | 
|  Add permissions to [AmazonECSServiceRolePolicy](https://docs.aws.amazon.com/AmazonECS/latest/developerguide/security-iam-awsmanpol.html#security-iam-awsmanpol-AmazonECSServiceRolePolicy).  | The AmazonECSServiceRolePolicy managed IAM policy was updated with new Amazon EC2 permissions which allow Amazon ECS to fetch Amazon EC2 Event Windows for services and clusters associated with Event Windows. | November 20, 2025 | 
|  Add permissions to [AmazonECSServiceRolePolicy](https://docs.aws.amazon.com/AmazonECS/latest/developerguide/security-iam-awsmanpol.html#security-iam-awsmanpol-AmazonECSServiceRolePolicy).  | The AmazonECSServiceRolePolicy managed IAM policy was updated with new Amazon EC2 permissions which allow Amazon ECS to provision and de-provision Task ENI. | November 14, 2025 | 
|  Update [AmazonECSInfrastructureRolePolicyForServiceConnectTransportLayerSecurity](https://docs.aws.amazon.com/AmazonECS/latest/developerguide/security-iam-awsmanpol.html#security-iam-awsmanpol-AmazonECSInfrastructureRolePolicyForServiceConnectTransportLayerSecurity) policy   | Updated the AmazonECSInfrastructureRolePolicyForServiceConnectTransportLayerSecurity managed IAM policy to separate the secretsmanager:DescribeSecret permission into its own policy statement. The permission continues to scope Amazon ECS access exclusively to secrets created by Amazon ECS and uses ARN pattern matching instead of resource tags for scoping. This allows Amazon ECS to monitor secret status throughout its lifecycle, including when a secret has been deleted. | November 13, 2025 | 
|  Add new [`AmazonECSInfrastructureRoleforExpressGatewayServices`](#security-iam-awsmanpol-AmazonECSInfrastructureRoleforExpressGatewayServices)  | Added new AmazonECSInfrastructureRoleforExpressGatewayServices policy that provides Amazon ECS access to create and manage web applications using Express Services. | November 21, 2025 | 
|  Add new [`AmazonECSInstanceRolePolicyForManagedInstances`](#security-iam-awsmanpol-AmazonECSInstanceRolePolicyForManagedInstances)  | Added new AmazonECSInstanceRolePolicyForManagedInstances policy that provides permissions for Amazon ECS managed instances to register with Amazon ECS clusters. | September 30, 2025 | 
|  Add new [`AmazonECSInfrastructureRolePolicyForManagedInstances`](#security-iam-awsmanpol-AmazonECSInfrastructureRolePolicyForManagedInstances)  | Added new AmazonECSInfrastructureRolePolicyForManagedInstances policy that provides Amazon ECS access to create and manage Amazon EC2 managed resources. | September, 30, 2025 | 
|  Add new [AmazonECSComputeServiceRolePolicy](https://docs.aws.amazon.com/AmazonECS/latest/developerguide/security-iam-awsmanpol.html#security-iam-awsmanpol-AmazonECSComputeServiceRolePolicy)  | Allows Amazon ECS to manage your Amazon ECS Managed Instances and related resources. | August 31, 2025 | 
|  Add permissions to [AmazonEC2ContainerServiceforEC2Role](#security-iam-awsmanpol-AmazonEC2ContainerServiceforEC2Role)   | The AmazonEC2ContainerServiceforEC2Role managed IAM policy was updated to include the ecs:ListTagsForResource permission. This permission allows the Amazon ECS agent to retrieve task and container instance tags through the task metadata endpoint (\$1\$1ECS\$1CONTAINER\$1METADATA\$1URI\$1V4\$1/taskWithTags). | August 4, 2025 | 
|  Add permissions to [AmazonECSInfrastructureRolePolicyForLoadBalancers](https://docs.aws.amazon.com/AmazonECS/latest/developerguide/security-iam-awsmanpol.html#security-iam-awsmanpol-AmazonECSInfrastructureRolePolicyForLoadBalancers).  | The AmazonECSInfrastructureRolePolicyForLoadBalancers managed IAM policy was updated with new permissions for describing, deregistering, and registering target groups. | July 25, 2025 | 
|  Add new [`AmazonECSInfrastructureRolePolicyForLoadBalancers`](#security-iam-awsmanpol-AmazonECSInfrastructureRolePolicyForLoadBalancers) policy  |  Added new AmazonECSInfrastructureRolePolicyForLoadBalancers policy that provides access to other AWS service resources required to manage load balancers associated with Amazon ECS workloads.  | July 15, 2025 | 
|  Add permissions to [AmazonECSServiceRolePolicy](https://docs.aws.amazon.com/AmazonECS/latest/developerguide/security-iam-awsmanpol.html#security-iam-awsmanpol-AmazonECSServiceRolePolicy).  | The AmazonECSServiceRolePolicy managed IAM policy was updated with new AWS Cloud Map permissions which Amazon ECS can update AWS Cloud Map service attributes for services that Amazon ECS manages. | July 15, 2025 | 
|  Add permissions to [AmazonECSServiceRolePolicy](https://docs.aws.amazon.com/AmazonECS/latest/developerguide/security-iam-awsmanpol.html#security-iam-awsmanpol-AmazonECSServiceRolePolicy)  | The AmazonECSServiceRolePolicy managed IAM policy was updated with new AWS Cloud Map permissions which Amazon ECS can update AWS Cloud Map service attributes for services that Amazon ECS manages. | June 24, 2025 | 
|  Add permissions to [AmazonECSInfrastructureRolePolicyForVolumes](https://docs.aws.amazon.com/AmazonECS/latest/developerguide/security-iam-awsmanpol.html#security-iam-awsmanpol-AmazonECSInfrastructureRolePolicyForVolumes)  | The AmazonECSInfrastructureRolePolicyForVolumes policy has been updated to add the ec2:DescribeInstances permission. The permission helps prevent device name collision for Amazon EBS volumes that are attached to Amazon ECS tasks that run on the same container instance. | June 2, 2025 | 
|  Add new [AmazonECSInfrastructureRolePolicyForVpcLattice](https://docs.aws.amazon.com/AmazonECS/latest/developerguide/security-iam-awsmanpol.html#security-iam-awsmanpol-AmazonECSInfrastructureRolePolicyForVpcLattice)  | Provides access to other AWS service resources required to manage VPC Lattice feature in Amazon ECS workloads on your behalf. | November 18, 2024 | 
|  Add permissions to [AmazonECSInfrastructureRolePolicyForVolumes](https://docs.aws.amazon.com/AmazonECS/latest/developerguide/security-iam-awsmanpol.html#security-iam-awsmanpol-AmazonECSInfrastructureRolePolicyForVolumes)  | The AmazonECSInfrastructureRolePolicyForVolumes policy has been updated to allow customers to create an Amazon EBS volume from a snapshot. | October 10, 2024 | 
|  Added permissions to [AmazonECS\$1FullAccess](#security-iam-awsmanpol-AmazonECS_FullAccess)  |  The AmazonECS\$1FullAccess policy was updated to add iam:PassRole permissions for IAM roles for a role named ecsInfrastructureRole. This is the default IAM role created by the AWS Management Console that is intended to be used as an ECS infrastructure role that allows Amazon ECS to manage Amazon EBS volumes attached to ECS tasks. | August 13, 2024 | 
|  Add new [AmazonECSInfrastructureRolePolicyForServiceConnectTransportLayerSecurity](https://docs.aws.amazon.com/AmazonECS/latest/developerguide/security-iam-awsmanpol.html#security-iam-awsmanpol-AmazonECSInfrastructureRolePolicyForServiceConnectTransportLayerSecurity) policy  |  Added new AmazonECSInfrastructureRolePolicyForServiceConnectTransportLayerSecurity policy that provides administrative access to AWS KMS, AWS Private Certificate Authority, Secrets Manager and enables Amazon ECS Service Connect TLS features to work properly.  | January 22, 2024 | 
|  Add new policy [AmazonECSInfrastructureRolePolicyForVolumes](https://docs.aws.amazon.com/AmazonECS/latest/developerguide/security-iam-awsmanpol.html#security-iam-awsmanpol-AmazonECSInfrastructureRolePolicyForVolumes)  | The AmazonECSInfrastructureRolePolicyForVolumes policy was added. The policy grants the permissions that are needed by Amazon ECS to make AWS API calls to manage Amazon EBS volumes associated with Amazon ECS workloads. | January 11, 2024 | 
|  Add permissions to [AmazonECSServiceRolePolicy](https://docs.aws.amazon.com/AmazonECS/latest/developerguide/security-iam-awsmanpol.html#security-iam-awsmanpol-AmazonECSServiceRolePolicy)  | The AmazonECSServiceRolePolicy managed IAM policy was updated with new events permissions and additional autoscaling and autoscaling-plans permissions. | December 4, 2023 | 
|  Add permissions to [AmazonEC2ContainerServiceEventsRole](https://docs.aws.amazon.com/AmazonECS/latest/developerguide/security-iam-awsmanpol.html#security-iam-awsmanpol-AmazonEC2ContainerServiceEventsRole)  | The AmazonECSServiceRolePolicy managed IAM policy was updated to allow access to the AWS Cloud Map DiscoverInstancesRevision API operation. | October 4, 2023 | 
|  Add permissions to [AmazonEC2ContainerServiceforEC2Role](https://docs.aws.amazon.com/AmazonECS/latest/developerguide/security-iam-awsmanpol.html#security-iam-awsmanpol-AmazonEC2ContainerServiceforEC2Role)  | The AmazonEC2ContainerServiceforEC2Role policy was modified to add the ecs:TagResource permission, which includes a condition that limits the permission only to newly created clusters and registered container instances. | March 6, 2023 | 
|  Add permissions to [AmazonECS\$1FullAccess](#security-iam-awsmanpol-AmazonECS_FullAccess)  | The AmazonECS\$1FullAccess policy was modified to add the elasticloadbalancing:AddTags permission, which includes a condition that limits the permission only to newly created load balancers, target groups, rules, and listeners created. This permission doesn't allow tags to be added to any already created Elastic Load Balancing resources. | January 4, 2023 | 
|  Amazon ECS started tracking changes  |  Amazon ECS started tracking changes for its AWS managed policies.  | June 8, 2021 | 

# Phased out AWS managed IAM policies for Amazon Elastic Container Service
AWS managed policies that are phased out for Amazon ECS

The following AWS managed IAM policies are phased out. These policies are now replaced by the updated policies. We recommend that you update your users or roles to use the updated policies.

## AmazonEC2ContainerServiceFullAccess


**Important**  
The `AmazonEC2ContainerServiceFullAccess` managed IAM policy was phased out as of January 29, 2021, in response to a security finding with the `iam:passRole` permission. This permission grants access to all resources including credentials to roles in the account. Now that the policy is phased out, you can't attach the policy to any new users or roles. Any users or roles that already have the policy attached can continue using it. However, we recommend that you update your users or roles to use the `AmazonECS_FullAccess` managed policy instead. For more information, see [Migrating to the `AmazonECS_FullAccess` managed policy](security-iam-awsmanpol-amazonecs-full-access-migration.md).

## AmazonEC2ContainerServiceRole


**Important**  
The `AmazonEC2ContainerServiceRole` managed IAM policy is phased out. It's now replaced by the Amazon ECS service-linked role. For more information, see [Using service-linked roles for Amazon ECS](using-service-linked-roles.md).

## AmazonEC2ContainerServiceAutoscaleRole


**Important**  
The `AmazonEC2ContainerServiceAutoscaleRole` managed IAM policy is phased out. It's now replaced by the Application Auto Scaling service-linked role for Amazon ECS. For more information, see [Service-linked roles for Application Auto Scaling](https://docs.aws.amazon.com/autoscaling/application/userguide/application-auto-scaling-service-linked-roles.html) in the *Application Auto Scaling User Guide*.

# Migrating to the `AmazonECS_FullAccess` managed policy
Migrating to AmazonECS\$1FullAccess

The `AmazonEC2ContainerServiceFullAccess` managed IAM policy was phased out on January 29, 2021, in response to a security finding with the `iam:passRole` permission. This permission grants access to all resources including credentials to roles in the account. Now that the policy is phased out, you can't attach the policy to any new groups, users, or roles. Any groups, users, or roles that already have the policy attached can continue using it. However, we recommend that you update your groups, users, or roles to use the `AmazonECS_FullAccess` managed policy instead.

The permissions that are granted by the `AmazonECS_FullAccess` policy include the complete list of permissions that are necessary to use ECS as an administrator. If you currently use permissions that are granted by the `AmazonEC2ContainerServiceFullAccess` policy that aren't in the `AmazonECS_FullAccess` policy, you can add them to an inline policy statement. For more information, see [AWS managed policies for Amazon Elastic Container Service](security-iam-awsmanpol.md).

Use the following steps to determine if you have any groups, users, or roles that are currently using the `AmazonEC2ContainerServiceFullAccess` managed IAM policy. Then, update them to detach the earlier policy and attach the `AmazonECS_FullAccess` policy.

**To update a group, user, or role to use the AmazonECS\$1FullAccess policy (AWS Management Console)**

1. Open the IAM console at [https://console.aws.amazon.com/iam/](https://console.aws.amazon.com/iam/).

1. In the navigation pane, choose **Policies** and search for and select the `AmazonEC2ContainerServiceFullAccess` policy.

1. Choose the **Policy usage** tab that displays any IAM role that's currently using this policy.

1. For each IAM role that's currently using the `AmazonEC2ContainerServiceFullAccess` policy, select the role and use the following steps to detach the phased out policy and attach the `AmazonECS_FullAccess` policy.

   1. On the **Permissions** tab, choose the **X** next to the **AmazonEC2ContainerServiceFullAccess** policy.

   1. Choose **Add permissions**.

   1. Choose **Attach existing policies directly**, search for and select the **AmazonECS\$1FullAccess** policy, and then choose **Next: Review**.

   1. Review the changes and then choose **Add permissions**.

   1. Repeat these steps for each group, user, or role that's using the `AmazonEC2ContainerServiceFullAccess` policy.

**To update a group, user, or role to use the `AmazonECS_FullAccess` policy (AWS CLI)**

1. Use the [https://docs.aws.amazon.com/cli/latest/reference/iam/generate-service-last-accessed-details.html](https://docs.aws.amazon.com/cli/latest/reference/iam/generate-service-last-accessed-details.html) command to generate a report that includes details about when the phased out policy was last used.

   ```
   aws iam generate-service-last-accessed-details \
        --arn arn:aws:iam::aws:policy/AmazonEC2ContainerServiceFullAccess
   ```

   Example output:

   ```
   {
       "JobId": "32bb1fb0-1ee0-b08e-3626-ae83EXAMPLE"
   }
   ```

1. Use the job ID from the previous output with the [https://docs.aws.amazon.com/cli/latest/reference/iam/get-service-last-accessed-details.html](https://docs.aws.amazon.com/cli/latest/reference/iam/get-service-last-accessed-details.html) command to retrieve the last accessed report of the service. This report displays the Amazon Resource Name (ARN) of the IAM entities that last used the phased out policy.

   ```
   aws iam get-service-last-accessed-details \
         --job-id 32bb1fb0-1ee0-b08e-3626-ae83EXAMPLE
   ```

1. Use one of the following commands to detach the `AmazonEC2ContainerServiceFullAccess` policy from a group, user, or role.
   + [https://docs.aws.amazon.com/cli/latest/reference/iam/detach-group-policy.html](https://docs.aws.amazon.com/cli/latest/reference/iam/detach-group-policy.html)
   + [https://docs.aws.amazon.com/cli/latest/reference/iam/detach-role-policy.html](https://docs.aws.amazon.com/cli/latest/reference/iam/detach-role-policy.html)
   + [https://docs.aws.amazon.com/cli/latest/reference/iam/detach-user-policy.html](https://docs.aws.amazon.com/cli/latest/reference/iam/detach-user-policy.html)

1. Use one of the following commands to attach the `AmazonECS_FullAccess` policy to a group, user, or role.
   + [https://docs.aws.amazon.com/cli/latest/reference/iam/attach-group-policy.html](https://docs.aws.amazon.com/cli/latest/reference/iam/attach-group-policy.html)
   + [https://docs.aws.amazon.com/cli/latest/reference/iam/attach-role-policy.html](https://docs.aws.amazon.com/cli/latest/reference/iam/attach-role-policy.html)
   + [https://docs.aws.amazon.com/cli/latest/reference/iam/attach-user-policy.html](https://docs.aws.amazon.com/cli/latest/reference/iam/attach-user-policy.html)

# Using service-linked roles for Amazon ECS
Using service-linked roles

Amazon Elastic Container Service uses AWS Identity and Access Management (IAM) [ service-linked roles](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_terms-and-concepts.html#iam-term-service-linked-role). A service-linked role is a unique type of IAM role that is linked directly to Amazon ECS. Service-linked roles are predefined by Amazon ECS and include all the permissions that the service requires to call other AWS services on your behalf.

**Topics**
+ [

# Using roles to allow Amazon ECS to manage clusters
](using-service-linked-roles-for-clusters.md)
+ [

# Using roles to manage Amazon ECS Managed Instances
](using-service-linked-roles-instances.md)

# Using roles to allow Amazon ECS to manage clusters
Allow Amazon ECS to manage clusters

Amazon Elastic Container Service uses AWS Identity and Access Management (IAM) [service-linked roles](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_terms-and-concepts.html#iam-term-service-linked-role). A service-linked role is a unique type of IAM role that is linked directly to Amazon ECS. Service-linked roles are predefined by Amazon ECS and include all the permissions that the service requires to call other AWS services on your behalf.

A service-linked role makes setting up Amazon ECS easier because you don’t have to manually add the necessary permissions. Amazon ECS defines the permissions of its service-linked roles, and unless defined otherwise, only Amazon ECS can assume its roles. The defined permissions include the trust policy and the permissions policy, and that permissions policy cannot be attached to any other IAM entity.

You can delete a service-linked role only after first deleting their related resources. This protects your Amazon ECS resources because you can't inadvertently remove permission to access the resources.

For information about other services that support service-linked roles, see [AWS services that work with IAM](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_aws-services-that-work-with-iam.html) and look for the services that have **Yes** in the **Service-linked roles** column. Choose a **Yes** with a link to view the service-linked role documentation for that service.

## Service-linked role permissions for Amazon ECS


Amazon ECS uses the service-linked role named **AWSServiceRoleForECS** – Role to allow Amazon ECS to manage your cluster.

The AWSServiceRoleForECS service-linked role trusts the following services to assume the role:
+ `ecs.amazonaws.com`

The role permissions policy named AmazonECSServiceRolePolicy allows Amazon ECS to complete the following actions on the specified resources:
+ Action: When using the `awsvpc` network mode for your Amazon ECS tasks, Amazon ECS manages the lifecycle of the elastic network interfaces associated with the task. This also includes tags that Amazon ECS adds to your elastic network interfaces.
+ Action: When using a load balancer with your Amazon ECS service, Amazon ECS manages the registration and deregistration of resources with the load balancer.
+ Action: When using Amazon ECS service discovery, Amazon ECS manages the required Route 53 and AWS Cloud Map resources for service discovery to work.
+ Action: When using Amazon ECS service auto scaling, Amazon ECS manages the required Auto Scaling resources.
+ Action: Amazon ECS creates and manages CloudWatch alarms and log streams that assist in the monitoring of your Amazon ECS resources.
+ Action: When using Amazon ECS Exec, Amazon ECS manages the permissions needed to start Amazon ECS Exec sessions to your tasks.
+ Action: When using Amazon ECS Service Connect, Amazon ECS manages the required AWS Cloud Map resources to use the feature.
+ Action: When using Amazon ECS capacity providers, Amazon ECS manages the permissions required to modify the Auto Scaling group and its Amazon EC2 instances.
+ Action: Amazon ECS can update AWS Cloud Map service attributes for services that Amazon ECS manages.
+ Action: Amazon ECS can invoke Amazon EC2 provision and de-provision ENI when starting and stopping tasks.
+ Action: Amazon ECS can fetch Amazon EC2 Event Windows for services and clusters associated with Event Windows.

You must configure permissions to allow your users, groups, or roles to create, edit, or delete a service-linked role. For more information, see [Service-linked role permissions](https://docs.aws.amazon.com/IAM/latest/UserGuide/using-service-linked-roles.html#service-linked-role-permissions) in the *IAM User Guide*.

## Creating a service-linked role for Amazon ECS


You don't need to manually create a service-linked role. When you create a cluster, or create or update a service in the AWS Management Console, the AWS CLI, or the AWS API, Amazon ECS creates the service-linked role for you. 

**Important**  
 This service-linked role can appear in your account if you completed an action in another service that uses the features supported by this role. If you were using the Amazon ECS service before January 1, 2017, when it began supporting service-linked roles, then Amazon ECS created the AWSServiceRoleForECS role in your account. To learn more, see [A new role appeared in my AWS account](https://docs.aws.amazon.com/IAM/latest/UserGuide/troubleshoot_roles.html#troubleshoot_roles_new-role-appeared).

You can also use the IAM console to create a service-linked role with the **AWSServiceRoleForECS** use case. In the AWS CLI or the AWS API, use IAM to create a service-linked role with the `ecs.amazonaws.com` service name. For more information, see [Creating a service-linked role](https://docs.aws.amazon.com/IAM/latest/UserGuide/using-service-linked-roles.html#create-service-linked-role) in the *IAM User Guide*. If you delete this service-linked role, you can use this same process to create the role again.

If you delete this service-linked role, and then need to create it again, you can use the same process to recreate the role in your account. When you create a cluster, or create or update a service, Amazon ECS creates the service-linked role for you again. 

If you delete this service-linked role, you can use the same IAM process to create the role again.

## Editing a service-linked role for Amazon ECS


Amazon ECS does not allow you to edit the AWSServiceRoleForECS service-linked role. After you create a service-linked role, you cannot change the name of the role because various entities might reference the role. However, you can edit the description of the role using IAM. For more information, see [Editing a service-linked role](https://docs.aws.amazon.com/IAM/latest/UserGuide/using-service-linked-roles.html#edit-service-linked-role) in the *IAM User Guide*.

## Deleting a service-linked role for Amazon ECS


You don't need to manually delete the AWSServiceRoleForECS role. When you delete clusters in all Regions in the AWS Management Console, the AWS CLI, or the AWS API, Amazon ECS cleans up the resources and deletes the service-linked role for you.

If you no longer need to use a feature or service that requires a service-linked role, we recommend that you delete that role. That way you don’t have an unused entity that is not actively monitored or maintained. However, you must clean up your service-linked role before you can manually delete it.

### Cleaning up a service-linked role


Before you can use IAM to delete a service-linked role, you must first delete any resources used by the role.

**Note**  
If the Amazon ECS service is using the role when you try to delete the resources, then the deletion might fail. If that happens, wait for a few minutes and try the operation again.

**To delete Amazon ECS resources used by the AWSServiceRoleForECS (console)**

1. Scale all Amazon ECS services down to a desired count of 0 in all regions, and then delete the services. For more information, see [Updating an Amazon ECS service](update-service-console-v2.md) and [Deleting an Amazon ECS service using the console](delete-service-v2.md).

1. Force deregister all container instances from all clusters in all Regions. For more information, see [Deregistering an Amazon ECS container instance](deregister_container_instance.md).

1. Delete all Amazon ECS clusters in all regions. For more information, see [Deleting an Amazon ECS cluster](delete_cluster-new-console.md).

**To delete Amazon ECS resources used by the AWSServiceRoleForECS (AWS CLI)**

1. Scale all Amazon ECS services down to a desired count of 0 in all regions, and then delete the services. For more information, see [update-service](https://docs.aws.amazon.com/cli/latest/reference/ecs/update-service.html) and [delete-service](https://docs.aws.amazon.com/cli/latest/reference/ecs/delete-service.html) in the AWS Command Line Interface Reference.

1. Force deregister all container instances from all clusters in all Regions. For more information, see [deregister-container-instance](https://docs.aws.amazon.com/cli/latest/reference/ecs/deregister-container-instance.html).

1. Delete all Amazon ECS clusters in all Regions. For more information, see [delete-cluster](https://docs.aws.amazon.com/cli/latest/reference/ecs/delete-cluster.html).

**To delete Amazon ECS resources used by the AWSServiceRoleForECS (API)**

1. Scale all Amazon ECS services down to a desired count of 0 in all regions, and then delete the services. For more information, see [UpdateService](https://docs.aws.amazon.com/AmazonECS/latest/APIReference/API_UpdateService.html) and [DeleteService](https://docs.aws.amazon.com/AmazonECS/latest/APIReference/API_DeleteService.html) in the *Amazon ECS API Reference*.

1. Force deregister all container instances from all clusters in all Regions. For more information, see [DeregisterContainerInstance](https://docs.aws.amazon.com/AmazonECS/latest/APIReference/API_DeregisterContainerInstance.html).

1. Delete all Amazon ECS clusters in all Regions. For more information, see [DeleteCluster](https://docs.aws.amazon.com/AmazonECS/latest/APIReference/API_DeleteCluster.html).

### Manually delete the service-linked role


Use the IAM console, the AWS CLI, or the AWS API to delete the AWSServiceRoleForECS service-linked role. For more information, see [Deleting a service-linked role](https://docs.aws.amazon.com/IAM/latest/UserGuide/using-service-linked-roles.html#delete-service-linked-role) in the *IAM User Guide*.

## Supported Regions for Amazon ECS service-linked roles


Amazon ECS supports using service-linked roles in all of the Regions where the service is available. For more information, see [AWS Regions and endpoints](https://docs.aws.amazon.com/general/latest/gr/rande.html).

# Using roles to manage Amazon ECS Managed Instances
Allow Amazon ECS to manage Amazon ECS Managed Instances

Amazon Elastic Container Service uses AWS Identity and Access Management (IAM) [service-linked roles](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_terms-and-concepts.html#iam-term-service-linked-role). A service-linked role is a unique type of IAM role that is linked directly to Amazon ECS. Service-linked roles are predefined by Amazon ECS and include all the permissions that the service requires to call other AWS services on your behalf.

A service-linked role makes setting up Amazon ECS easier because you don’t have to manually add the necessary permissions. Amazon ECS defines the permissions of its service-linked roles, and unless defined otherwise, only Amazon ECS can assume its roles. The defined permissions include the trust policy and the permissions policy, and that permissions policy cannot be attached to any other IAM entity.

You can delete a service-linked role only after first deleting their related resources. This protects your Amazon ECS resources because you can't inadvertently remove permission to access the resources.

For information about other services that support service-linked roles, see [AWS services that work with IAM](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_aws-services-that-work-with-iam.html) and look for the services that have **Yes** in the **Service-linked roles** column. Choose a **Yes** with a link to view the service-linked role documentation for that service.

## Service-linked role permissions for Amazon ECS


Amazon ECS uses the service-linked role named **AWSServiceRoleForECSCompute** – Role to allow Amazon ECS to manage Amazon EC2 managed instances, provisioned by the Amazon ECS Managed Instances capacity provider.

The AWSServiceRoleForECSCompute service-linked role trusts the following services to assume the role:
+ `ecs-compute.amazonaws.com`

The role permissions policy named [`AmazonECSComputeServiceRolePolicy`](security-iam-awsmanpol.md#security-iam-awsmanpol-AmazonECSComputeServiceRolePolicy) allows Amazon ECS complete the following tasks:
+ Amazon ECS can describe and delete launch templates.
+  Amazon ECS can describe and delete launch template versions.
+ Amazon ECS can terminate instances.
+ Amazon ECS can describe the following instance data parameters:
  + Instance
  + Instance network interfaces: Amazon ECS can describe the the to manage the EC2 instance lifecycle.
  + Instance event window: Amazon ECS can describe the event window information in order to determine if the workflow can be interrupted for patching the instance.
  + Instance status: Amazon ECS can describe the instance status in order to monitor the instance health.

You must configure permissions to allow your users, groups, or roles to create, edit, or delete a service-linked role. For more information, see [Service-linked role permissions](https://docs.aws.amazon.com/IAM/latest/UserGuide/using-service-linked-roles.html#service-linked-role-permissions) in the *IAM User Guide*.

## Creating a service-linked role for Amazon ECS


You don't need to manually create a service-linked role. When you create a capacity provider for Amazon ECS Managed Instances in the AWS Management Console, the AWS CLI, or the AWS API, Amazon ECS creates the service-linked role for you. 

**Important**  
 This service-linked role can appear in your account if you completed an action in another service that uses the features supported by this role. If you were using the Amazon ECS service before January 1, 2017, when it began supporting service-linked roles, then Amazon ECS created the AmazonECSComputeServiceRolePolicy role in your account. To learn more, see [A new role appeared in my AWS account](https://docs.aws.amazon.com/IAM/latest/UserGuide/troubleshoot_roles.html#troubleshoot_roles_new-role-appeared).

If you delete this service-linked role, and then need to create it again, you can use the same process to recreate the role in your account. When you create a capacity provider for Amazon ECS Managed Instances, Amazon ECS creates the service-linked role for you again. 

If you delete this service-linked role, you can use the same IAM process to create the role again.

## Editing a service-linked role for Amazon ECS


Amazon ECS does not allow you to edit the AmazonECSComputeServiceRolePolicy service-linked role. After you create a service-linked role, you cannot change the name of the role because various entities might reference the role. However, you can edit the description of the role using IAM. For more information, see [Editing a service-linked role](https://docs.aws.amazon.com/IAM/latest/UserGuide/using-service-linked-roles.html#edit-service-linked-role) in the *IAM User Guide*.

## Deleting a service-linked role for Amazon ECS


You don't need to manually delete the AmazonECSComputeServiceRolePolicy role. When you delete all Amazon ECS Managed Instances capacity providers in all Regions in the AWS Management Console, the AWS CLI, or the AWS API, Amazon ECS cleans up the resources and deletes the service-linked role for you.

### Manually delete the service-linked role


Use the IAM console, the AWS CLI, or the AWS API to delete the AmazonECSComputeServiceRolePolicy service-linked role. For more information, see [Deleting a service-linked role](https://docs.aws.amazon.com/IAM/latest/UserGuide/using-service-linked-roles.html#delete-service-linked-role) in the *IAM User Guide*.

## Supported Regions for Amazon ECS service-linked roles


Amazon ECS supports using service-linked roles in all of the Regions where the service is available. For more information, see [AWS Regions and endpoints](https://docs.aws.amazon.com/general/latest/gr/rande.html).

# IAM roles for Amazon ECS


An IAM role is an IAM identity that you can create in your account that has specific permissions. In Amazon ECS, you can create roles to grant permissions to Amazon ECS resource such as containers or services.

The roles Amazon ECS requires depend on the task definition launch type and the features that you use. Use the following table to determine which IAM roles you need for Amazon ECS.


| Role | Definition | When required | More information | 
| --- | --- | --- | --- | 
| Task execution role | This role allows Amazon ECS to use other AWS services on your behalf. |  Your task is hosted on AWS Fargate or on external instances and: [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/AmazonECS/latest/developerguide/security-ecs-iam-role-overview.html) Your task is hosted on either AWS Fargate or Amazon EC2 instances and: [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/AmazonECS/latest/developerguide/security-ecs-iam-role-overview.html)  | [Amazon ECS task execution IAM role](task_execution_IAM_role.md) | 
| Task role | This role allows your application code (on the container) to use other AWS services. | Your application accesses other AWS services, such as Amazon S3. | [Amazon ECS task IAM role](task-iam-roles.md) | 
| Container instance role | This role allows your EC2 instances or external instances to register with the cluster. | Your task is hosted on Amazon EC2 instances or an external instance. | [Amazon ECS container instance IAM role](instance_IAM_role.md) | 
| Amazon ECS Anywhere role | This role allows your external instances to access AWS APIs. | Your task is hosted on external instances. | [Amazon ECS Anywhere IAM role](iam-role-ecsanywhere.md) | 
| Amazon ECS infrastructure for load balancers role | This role allows Amazon ECS to manage load balancer resources in your clusters on your behalf for blue/green deployments. | You want to use Amazon ECS blue/green deployments. | [Amazon ECS infrastructure IAM role for load balancers](AmazonECSInfrastructureRolePolicyForLoadBalancers.md) | 
| Amazon ECS CodeDeploy role | This role allows CodeDeploy to make updates to your services. | You use the CodeDeploy blue/green deployment type to deploy services. | [Amazon ECS CodeDeploy IAM Role](codedeploy_IAM_role.md) | 
| Amazon ECS EventBridge role | This role allows EventBridge to make updates to your services. | You use the EventBridge rules and targets to schedule your tasks. | [Amazon ECS EventBridge IAM Role](CWE_IAM_role.md) | 
| Amazon ECS infrastructure role | This role allows Amazon ECS to manage infrastructure resources in your clusters.  |  [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/AmazonECS/latest/developerguide/security-ecs-iam-role-overview.html) | [Amazon ECS infrastructure IAM role](infrastructure_IAM_role.md) | 
| Instance profile | This role allows allows Amazon ECS Managed Instances to assume the infrastructure role securely. | You use Amazon ECS Managed Instances in your clusters. | [Amazon ECS Managed Instances instance profile](managed-instances-instance-profile.md) | 

# Best practices for IAM roles in Amazon ECS
Best practices for IAM roles

The roles Amazon ECS requires depend on the task definition launch type and the features that you use. We recommend that you create separate roles in the table instead of sharing roles.


| Role | Definition | When required | More information | 
| --- | --- | --- | --- | 
| Task execution role | This role allows Amazon ECS to use other AWS services on your behalf. |  Your task is hosted on AWS Fargate or on external instances and: [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/AmazonECS/latest/developerguide/security-iam-roles.html) Your task is hosted on either AWS Fargate or Amazon EC2 instances and: [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/AmazonECS/latest/developerguide/security-iam-roles.html)  | [Amazon ECS task execution IAM role](task_execution_IAM_role.md) | 
| Task role | This role allows your application code (on the container) to use other AWS services. | Your application accesses other AWS services, such as Amazon S3. | [Amazon ECS task IAM role](task-iam-roles.md) | 
| Container instance role | This role allows your EC2 instances or external instances to register with the cluster. | Your task is hosted on Amazon EC2 instances or an external instance. | [Amazon ECS container instance IAM role](instance_IAM_role.md) | 
| Amazon ECS Anywhere role | This role allows your external instances to access AWS APIs. | Your task is hosted on external instances. | [Amazon ECS Anywhere IAM role](iam-role-ecsanywhere.md) | 
| Amazon ECS CodeDeploy role | This role allows CodeDeploy to make updates to your services. | You use the CodeDeploy blue/green deployment type to deploy services. | [Amazon ECS CodeDeploy IAM Role](codedeploy_IAM_role.md) | 
| Amazon ECS EventBridge role | This role allows EventBridge to make updates to your services. | You use the EventBridge rules and targets to schedule your tasks. | [Amazon ECS EventBridge IAM Role](CWE_IAM_role.md) | 
| Amazon ECS infrastructure role | This role allows Amazon ECS to manage infrastructure resources in your clusters.  |  [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/AmazonECS/latest/developerguide/security-iam-roles.html) | [Amazon ECS infrastructure IAM role](infrastructure_IAM_role.md) | 

## Task role


We recommend that you assign a task role. Its role can be distinguished from the role of the Amazon EC2 instance that it's running on. Assigning each task a role aligns with the principle of least privileged access and allows for greater granular control over actions and resources.

When you add a task role to a task definition, the Amazon ECS container agent automatically creates a token with a unique credential ID (for example, `12345678-90ab-cdef-1234-567890abcdef`) for the task. This token and the role credentials are then added to the agent's internal cache. The agent populates the environment variable `AWS_CONTAINER_CREDENTIALS_RELATIVE_URI` in the container with the URI of the credential ID (for example, `/v2/credentials/12345678-90ab-cdef-1234-567890abcdef`).

You can manually retrieve the temporary role credentials from inside a container by appending the environment variable to the IP address of the Amazon ECS container agent and running the `curl` command on the resulting string.

```
curl 169.254.170.2$AWS_CONTAINER_CREDENTIALS_RELATIVE_URI
```

The expected output is as follows:

```
{
	"RoleArn": "arn:aws:iam::123456789012:role/SSMTaskRole-SSMFargateTaskIAMRole-DASWWSF2WGD6",
	"AccessKeyId": "AKIAIOSFODNN7EXAMPLE",
	"SecretAccessKey": "wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY",
	"Token": "IQoJb3JpZ2luX2VjEEM/Example==",
	"Expiration": "2021-01-16T00:51:53Z"
}
```

Newer versions of the AWS SDKs automatically fetch these credentials from the `AWS_CONTAINER_CREDENTIALS_RELATIVE_URI` environment variable when making AWS API calls. For information about how to renew credentials, see [Renewing AWS credentials](https://repost.aws/questions/QUgcf1EIOPS7GZNboeAiyO9Q/renewing-aws-credentials) on rePost.

The output includes an access key-pair consisting of a secret access key ID and a secret key which your application uses to access AWS resources. It also includes a token that AWS uses to verify that the credentials are valid. By default, credentials assigned to tasks using task roles are valid for six hours. After that, they are automatically rotated by the Amazon ECS container agent.

## Task execution role


The task execution role is used to grant the Amazon ECS container agent permission to call specific AWS API actions on your behalf. For example, when you use AWS Fargate, Fargate needs an IAM role that allows it to pull images from Amazon ECR and write logs to CloudWatch Logs. An IAM role is also required when a task references a secret that's stored in AWS Secrets Manager, such as an image pull secret.

**Note**  
If you're pulling images as an authenticated user, you're less likely to be impacted by the changes that occurred to [Docker Hub's pull rate limits](https://www.docker.com/pricing/resource-consumption-updates). For more information see, [Private registry authentication for container instances](https://docs.aws.amazon.com/AmazonECS/latest/developerguide/private-auth-container-instances.html).  
By using Amazon ECR and Amazon ECR Public, you can avoid the limits imposed by Docker. If you pull images from Amazon ECR, this also helps shorten network pull times and reduces data transfer changes when traffic leaves your VPC.

**Important**  
When you use Fargate, you must authenticate to a private image registry using `repositoryCredentials`. It's not possible to set the Amazon ECS container agent environment variables `ECS_ENGINE_AUTH_TYPE` or `ECS_ENGINE_AUTH_DATA` or modify the `ecs.config` file for tasks hosted on Fargate. For more information, see [Private registry authentication for tasks](https://docs.aws.amazon.com/AmazonECS/latest/developerguide/private-auth.html).

## Container instance role


The `AmazonEC2ContainerServiceforEC2Role` managed IAM policy includes the following permissions. Following the standard security advice of granting least privilege, the `AmazonEC2ContainerServiceforEC2Role` managed policy can be used as a guide. If you don't need any of the permissions that are granted in the managed policy for your use case, create a custom policy and add only the permissions that you need.
+ `ec2:DescribeTags` – (Optional) Allows a principal to describe the tags that are associated with an Amazon EC2 instance. This permission is used by the Amazon ECS container agent to support resource tag propagation. For more information, see [How resources are tagged](ecs-using-tags.md#tag-resources).
+ `ecs:CreateCluster` – (Optional) Allows a principal to create an Amazon ECS cluster. This permission is used by the Amazon ECS container agent to create a `default` cluster, if one doesn't already exist.
+ `ecs:DeregisterContainerInstance` – (Optional) Allows a principal to deregister an Amazon ECS container instance from a cluster. The Amazon ECS container agent doesn't call this API operation, but this permission remains to help ensure backwards compatibility.
+ `ecs:DiscoverPollEndpoint` – (Required) This action returns endpoints that the Amazon ECS container agent uses to poll for updates.
+ `ecs:Poll` – (Required) Allows the Amazon ECS container agent to communicate with the Amazon ECS control plane to report task state changes.
+ `ecs:RegisterContainerInstance` – (Required) Allows a principal to register a container instance with a cluster. This permission is used by the Amazon ECS container agent to register the Amazon EC2 instance with a cluster and to support resource tag propagation.
+ `ecs:StartTelemetrySession` – (Optional) Allows the Amazon ECS container agent to communicate with the Amazon ECS control plane to report health information and metrics for each container and task.

  Although this permission is not required, we recommend that you add it to allowthe container instance metrics to start scale actions and also receive reports related to health check commands.
+ `ecs:TagResource` – (Optional) Allows the Amazon ECS container agent to tag cluster on creation and to tag container instances when they are registered to a cluster.
+ `ecs:UpdateContainerInstancesState` – Allows a principal to modify the status of an Amazon ECS container instance. This permission is used by the Amazon ECS container agent for Spot Instance draining. 
+ `ecs:Submit*` – (Required) This includes the `SubmitAttachmentStateChanges`, `SubmitContainerStateChange`, and `SubmitTaskStateChange` API actions. They're used by the Amazon ECS container agent to report state changes for each resource to the Amazon ECS control plane. The `SubmitContainerStateChange` permission is no longer used by the Amazon ECS container agent but remains to help ensure backwards compatibility.
+ `ecr:GetAuthorizationToken` – (Optional) Allows a principal to retrieve an authorization token. The authorization token represents your IAM authentication credentials and can be used to access any Amazon ECR registry that the IAM principal has access to. The authorization token received is valid for 12 hours.
+ `ecr:BatchCheckLayerAvailability` – (Optional) When a container image is pushed to an Amazon ECR private repository, each image layer is checked to verify if it's already pushed. If it is, then the image layer is skipped.
+ `ecr:GetDownloadUrlForLayer` – (Optional) When a container image is pulled from an Amazon ECR private repository, this API is called once for each image layer that's not already cached.
+ `ecr:BatchGetImage` – (Optional) When a container image is pulled from an Amazon ECR private repository, this API is called once to retrieve the image manifest.
+ `logs:CreateLogStream` – (Optional) Allows a principal to create a CloudWatch Logs log stream for a specified log group.
+ `logs:PutLogEvents` – (Optional) Allows a principal to upload a batch of log events to a specified log stream.

## Service-linked roles


You can use the service-linked role for Amazon ECS to grant the Amazon ECS service permission to call other service APIs on your behalf. Amazon ECS needs the permissions to create and delete network interfaces, register, and de-register targets with a target group. It also needs the necessary permissions to create and delete scaling policies. These permissions are granted through the service-linked role. This role is created on your behalf the first time that you use the service.

**Note**  
If you inadvertently delete the service-linked role, you can recreate it. For instructions, see [Create the service-linked role](https://docs.aws.amazon.com/AmazonECS/latest/developerguide/using-service-linked-roles.html#create-service-linked-role).

## Roles recommendations


We recommend that you do the following when setting up your task IAM roles and policies.

### Block access to Amazon EC2 metadata


When you run your tasks on Amazon EC2 instances, we strongly recommend that you block access to Amazon EC2 metadata to prevent your containers from inheriting the role assigned to those instances. If your applications have to call an AWS API action, use IAM roles for tasks instead.

To prevent tasks running in **bridge** mode from accessing Amazon EC2 metadata, run the following command or update the instance's user data. For more instruction on updating the user data of an instance, see this [AWS Support Article](https://aws.amazon.com/premiumsupport/knowledge-center/ecs-container-ec2-metadata/). For more information about the task definition bridge mode, see [task definition network mode](https://docs.aws.amazon.com/AmazonECS/latest/developerguide/task_definition_parameters.html#network_mode).

```
sudo yum install -y iptables-services; sudo iptables --insert FORWARD 1 --in-interface docker+ --destination 169.254.169.254/32 --jump DROP
```

For this change to persist after a reboot, run the following command that's specific for your Amazon Machine Image (AMI):
+ Amazon Linux 2

  ```
  sudo iptables-save | sudo tee /etc/sysconfig/iptables && sudo systemctl enable --now iptables
  ```
+ Amazon Linux

  ```
  sudo service iptables save
  ```

For tasks that use `awsvpc` network mode, set the environment variable `ECS_AWSVPC_BLOCK_IMDS` to `true` in the `/etc/ecs/ecs.config` file.

You should set the `ECS_ENABLE_TASK_IAM_ROLE_NETWORK_HOST` variable to `false` in the `ecs-agent config` file to prevent the containers that are running within the `host` network from accessing the Amazon EC2 metadata.

### Use the `awsvpc` network mode


Use the network `awsvpc` network mode to restrict the flow of traffic between different tasks or between your tasks and other services that run within your Amazon VPC. This adds an additional layer of security. The `awsvpc` network mode provides task-level network isolation for tasks that run on Amazon EC2. It is the default mode on AWS Fargate. it's the only network mode that you can use to assign a security group to tasks. 

### Use last accessed information to refine roles


We recommend that you remove any actions that were never used or haven't been used for some time. This prevents unwanted access from happening. To do this, review last accessed information provided by IAM, and then remove actions that were never used or haven't been used recently. You can do this by following the following steps.

Run the following command to generate a report showing the last access information for the referenced policy:

```
aws iam generate-service-last-accessed-details --arn arn:aws:iam::123456789012:policy/ExamplePolicy1
```

use the `JobId` that was in the output to run the following command. After you do this, you can view the results of the report.

```
aws iam get-service-last-accessed-details --job-id 98a765b4-3cde-2101-2345-example678f9
```

For more information, see [Refine permissions in AWS using last accessed information](https://docs.aws.amazon.com/IAM/latest/UserGuide/access_policies_last-accessed.html).

### Monitor AWS CloudTrail for suspicious activity


You can monitor AWS CloudTrail for any suspicious activity. Most AWS API calls are logged to AWS CloudTrail as events. They are analyzed by AWS CloudTrail Insights, and you're alerted of any suspicious behavior that's associated with `write` API calls. This might include a spike in call volume. These alerts include such information as the time the unusual activity occurred and the top identity ARN that contributed to the APIs. 

You can identify actions that are performed by tasks with an IAM role in AWS CloudTrail by looking at the event's `userIdentity` property. In the following example, the `arn` includes of the name of the assumed role, `s3-write-go-bucket-role`, followed by the name of the task, `7e9894e088ad416eb5cab92afExample`.

```
"userIdentity": {
    "type": "AssumedRole",
    "principalId": "AROA36C6WWEJ2YEXAMPLE:7e9894e088ad416eb5cab92afExample",
    "arn": "arn:aws:sts::123456789012:assumed-role/s3-write-go-bucket-role/7e9894e088ad416eb5cab92afExample",
    ...
}
```

**Note**  
When tasks that assume a role are run on Amazon EC2 container instances, a request is logged by Amazon ECS container agent to the audit log of the agent that's located at an address in the `/var/log/ecs/audit.log.YYYY-MM-DD-HH` format. For more information, see [Task IAM Roles Log](https://docs.aws.amazon.com/AmazonECS/latest/developerguide/logs.html#task_iam_roles-logs) and [Logging Insights Events for Trails](https://docs.aws.amazon.com/awscloudtrail/latest/userguide/logging-insights-events-with-cloudtrail.html).

# Amazon ECS task execution IAM role
Task execution IAM role

The task execution role grants the Amazon ECS container and Fargate agents permission to make AWS API calls on your behalf. The task execution IAM role is required depending on the requirements of your task. You can have multiple task execution roles for different purposes and services associated with your account.

**Note**  
These permissions are made available to the agent running on your instance by Amazon ECS periodically sending it the role's temporary credentials, but they aren't directly accessible by the containers in the task. For the IAM permissions that your application code inside the container needs to run, see [Amazon ECS task IAM role](task-iam-roles.md). 

The following are common use cases for a task execution IAM role:
+ Your task is hosted on AWS Fargate, Amazon ECS Managed Instances, or an external instance and:
  + pulls a container image from an Amazon ECR private repository.
  + pulls a container image from an Amazon ECR private repository in a different account from the account that runs the task.
  + sends container logs to CloudWatch Logs using the `awslogs` log driver. For more information, see [Send Amazon ECS logs to CloudWatch](using_awslogs.md).
+ Your tasks are hosted on either AWS Fargate or Amazon EC2 instances and:
  + uses private registry authentication. For more information, see [Private registry authentication permissions](#task-execution-private-auth).
  + uses Runtime Monitoring.
  + the task definition references sensitive data using Secrets Manager secrets or AWS Systems Manager Parameter Store parameters. For more information, see [Secrets Manager or Systems Manager permissions](#task-execution-secrets).

**Note**  
The task execution role is supported by Amazon ECS container agent version 1.16.0 and later.

Amazon ECS provides the managed policy named `AmazonECSTaskExecutionRolePolicy` which contains the permissions the common use cases described above require. For more information, see [AmazonECSTaskExecutionRolePolicy](https://docs.aws.amazon.com/aws-managed-policy/latest/reference/AmazonECSTaskExecutionRolePolicy.html) in the *AWS Managed Policy Reference Guide*. It might be necessary to add inline policies to your task execution role for special use cases

The Amazon ECS console creates a task execution role. You can manually attach the managed IAM policy for tasks to allow Amazon ECS to add permissions for future features and enhancements as they are introduced. You can use IAM console search to search for `ecsTaskExecutionRole` and see if your account already has the task execution role. For more information, see [IAM console search](https://docs.aws.amazon.com/IAM/latest/UserGuide/console_search.html) in the *IAM user guide*.

If you pull images as an authenticated user, you're less likely to be impacted by the changes that occurred to [Docker Hub usage and limits](https://docs.docker.com/docker-hub/usage/). For more information see, [Private registry authentication for container instances](https://docs.aws.amazon.com/AmazonECS/latest/developerguide/private-auth-container-instances.html).

By using Amazon ECR and Amazon ECR Public, you can avoid the limits imposed by Docker. If you pull images from Amazon ECR, this also helps shorten network pull times and reduces data transfer changes when traffic leaves your VPC.

When you use Fargate, you must authenticate to a private image registry using `repositoryCredentials`. It's not possible to set the Amazon ECS container agent environment variables `ECS_ENGINE_AUTH_TYPE` or `ECS_ENGINE_AUTH_DATA` or modify the `ecs.config` file for tasks hosted on Fargate. For more information, see [Private registry authentication for tasks](https://docs.aws.amazon.com/AmazonECS/latest/developerguide/private-auth.html).

## Creating the task execution role


If your account doesn't already have a task execution role, use the following steps to create the role.

------
#### [ AWS Management Console ]

**To create the service role for Elastic Container Service (IAM console)**

1. Sign in to the AWS Management Console and open the IAM console at [https://console.aws.amazon.com/iam/](https://console.aws.amazon.com/iam/).

1. In the navigation pane of the IAM console, choose **Roles**, and then choose **Create role**.

1. For **Trusted entity type**, choose **AWS service**.

1. For **Service or use case**, choose **Elastic Container Service**, and then choose the **Elastic Container Service Task** use case.

1. Choose **Next**.

1. In the **Add permissions** section, search for **AmazonECSTaskExecutionRolePolicy**, then select the policy.

1. Choose **Next**.

1.  For **Role name**, enter **ecsTaskExecutionRole**.

1. Review the role, and then choose **Create role**.

------
#### [ AWS CLI ]

Replace all *user input* with your own information.

1. Create a file named `ecs-tasks-trust-policy.json` that contains the trust policy to use for the IAM role. The file should contain the following:

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

****  

   ```
   {
     "Version":"2012-10-17",		 	 	 
     "Statement": [
       {
         "Sid": "",
         "Effect": "Allow",
         "Principal": {
           "Service": "ecs-tasks.amazonaws.com"
         },
         "Action": "sts:AssumeRole"
       }
     ]
   }
   ```

------

1. Create an IAM role named `ecsTaskExecutionRole` using the trust policy created in the previous step.

   ```
   aws iam create-role \
         --role-name ecsTaskExecutionRole \
         --assume-role-policy-document file://ecs-tasks-trust-policy.json
   ```

1. Attach the AWS managed `AmazonECSTaskExecutionRolePolicy` policy to the `ecsTaskExecutionRole` role.

   ```
   aws iam attach-role-policy \
         --role-name ecsTaskExecutionRole \
         --policy-arn arn:aws:iam::aws:policy/service-role/AmazonECSTaskExecutionRolePolicy
   ```

------

After you create the role, add additional permissions to the role for the following features.


|  Feature  |  Additional permissions  | 
| --- | --- | 
|  Pull container images from private registries outside of AWS (such as Docker Hub, Quay.io, or your own private registry) using Secrets Manager credentials  |  [Private registry authentication permissions](#task-execution-private-auth)  | 
| Pass sensitive data with Systems Manager or Secrets Manager | [Secrets Manager or Systems Manager permissions](#task-execution-secrets) | 
| Have Fargate tasks pull Amazon ECR images over interface endpoints | [Fargate tasks pulling Amazon ECR images over interface endpoints permissions](#task-execution-ecr-conditionkeys) | 
| Host configuration files in an Amazon S3 bucket | [Amazon S3 file storage permissions](#s3-required) | 
| Configure Container Insights to view Amazon ECS lifecycle events |  [Permissions required for enabling Amazon ECS lifecycle events in Container Insights](console-permissions.md#required-permissions-configure)  | 
| View Amazon ECS lifecycle events in Container Insights |  [Permissions required to view Amazon ECS lifecycle events in Container Insights](console-permissions.md#required-permissions-view)  | 

## Private registry authentication permissions


Private registry authentication allows your Amazon ECS tasks to pull container images from private registries outside of AWS (such as Docker Hub, Quay.io, or your own private registry) that require authentication credentials. This feature uses Secrets Manager to securely store your registry credentials, which are then referenced in your task definition using the `repositoryCredentials` parameter.

For more information about configuring private registry authentication, see [Using non-AWS container images in Amazon ECS](https://docs.aws.amazon.com/AmazonECS/latest/developerguide/private-auth.html).

To provide access to the secrets that contain your private registry credentials, add the following permissions as an inline policy to the task execution role. For more information, see [Adding and Removing IAM Policies](https://docs.aws.amazon.com/IAM/latest/UserGuide/access_policies_manage-attach-detach.html).
+ `secretsmanager:GetSecretValue`—Required to retrieve the private registry credentials from Secrets Manager.
+ `kms:Decrypt`—Required only if your secret uses a custom KMS key and not the default key. The Amazon Resource Name (ARN) for your custom key must be added as a resource.

The following is an example inline policy that adds the permissions.

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

****  

```
{
    "Version":"2012-10-17",		 	 	 
    "Statement": [
        {
            "Effect": "Allow",
            "Action": [
                "kms:Decrypt",
                "secretsmanager:GetSecretValue"
            ],
            "Resource": [
                "arn:aws:secretsmanager:us-east-1:111122223333:secret:secret_name",
                "arn:aws:kms:us-east-1:111122223333:key/key_id"
            ]
        }
    ]
}
```

------

## Secrets Manager or Systems Manager permissions


The permission to allow the container agent to pull the necessary AWS Systems Manager or Secrets Manager resources. For more information, see [Pass sensitive data to an Amazon ECS container](specifying-sensitive-data.md).

**Using Secrets Manager **

To provide access to the Secrets Manager secrets that you create, manually add the following permission to the task execution role. For information about how to manage permissions, see [Adding and Removing IAM identity permissions](https://docs.aws.amazon.com/IAM/latest/UserGuide/access_policies_manage-attach-detach.html) in the *IAM User Guide*.
+ `secretsmanager:GetSecretValue`– Required if you are referencing a Secrets Manager secret. Adds the permission to retrieve the secret from Secrets Manager.

The following example policy adds the required permissions.

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

****  

```
{
  "Version":"2012-10-17",		 	 	 
  "Statement": [
    {
      "Effect": "Allow",
      "Action": [
        "secretsmanager:GetSecretValue"
      ],
      "Resource": [
        "arn:aws:secretsmanager:us-east-1:111122223333:secret:secret_name"
      ]
    }
  ]
}
```

------

**Using Systems Manager**

**Important**  
For tasks that use the EC2 launch type, you must use the ECS agent configuration variable `ECS_ENABLE_AWSLOGS_EXECUTIONROLE_OVERRIDE=true` to use this feature. You can add it to the `./etc/ecs/ecs.config` file during container instance creation or you can add it to an existing instance and then restart the ECS agent. For more information, see [Amazon ECS container agent configuration](ecs-agent-config.md).

To provide access to the Systems Manager Parameter Store parameters that you create, manually add the following permissions as a policy to the task execution role. For information about how to manage permissions, see [Adding and Removing IAM identity permissions](https://docs.aws.amazon.com/IAM/latest/UserGuide/access_policies_manage-attach-detach.html) in the *IAM User Guide*.
+ `ssm:GetParameters` — Required if you are referencing a Systems Manager Parameter Store parameter in a task definition. Adds the permission to retrieve Systems Manager parameters.
+ `secretsmanager:GetSecretValue` — Required if you are referencing a Secrets Manager secret either directly or if your Systems Manager Parameter Store parameter is referencing a Secrets Manager secret in a task definition. Adds the permission to retrieve the secret from Secrets Manager.
+ `kms:Decrypt` — Required only if your secret uses a customer managed key and not the default key. The ARN for your custom key should be added as a resource. Adds the permission to decrypt the customer managed key .

The following example policy adds the required permissions:

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

****  

```
{
  "Version":"2012-10-17",		 	 	 
  "Statement": [
    {
      "Effect": "Allow",
      "Action": [
        "ssm:GetParameters",
        "secretsmanager:GetSecretValue",
        "kms:Decrypt"
      ],
      "Resource": [
        "arn:aws:ssm:us-east-1:111122223333:parameter/parameter_name",
        "arn:aws:secretsmanager:us-east-1:111122223333:secret:secret_name",
        "arn:aws:kms:us-east-1:111122223333:key/key_id"
      ]
    }
  ]
}
```

------

## Fargate tasks pulling Amazon ECR images over interface endpoints permissions


When launching tasks that use Fargate that pull images from Amazon ECR when Amazon ECR is configured to use an interface VPC endpoint, you can restrict the tasks access to a specific VPC or VPC endpoint. Do this by creating a task execution role for the tasks to use that use IAM condition keys.

Use the following IAM global condition keys to restrict access to a specific VPC or VPC endpoint. For more information, see [AWS Global Condition Context Keys](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_condition-keys.html).
+ `aws:SourceVpc`—Restricts access to a specific VPC. You can restrict the VPC to the VPC that hosts the task and endpoint.
+ `aws:SourceVpce`—Restricts access to a specific VPC endpoint.

The following task execution role policy provides an example for adding condition keys:

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

****  

```
{
    "Version":"2012-10-17",		 	 	 
    "Statement": [
            {
                "Effect": "Allow",
                "Action": [
                    "ecr:GetAuthorizationToken",
                    "logs:CreateLogStream",
                    "logs:PutLogEvents"
                ],
                "Resource": "*"
            },
            {
                "Effect": "Allow",
                "Action": [
                    "ecr:BatchCheckLayerAvailability",
                    "ecr:GetDownloadUrlForLayer",
                    "ecr:BatchGetImage"
                ],
                "Resource": "arn:aws:ecr:*:*:repository/*",
                "Condition": {
                    "StringEquals": {
                            "aws:sourceVpce": "vpce-0123456789abcdef0"
                    }
                }
            }
    ]
}
```

------

## Amazon ECR permissions


The following permissions are required when you need to pull container images from Amazon ECR private repositories. The task execution role should have these permissions to allow the Amazon ECS container and Fargate agents to pull container images on your behalf. For basic ECS implementations, these permissions should be added to the task execution role rather than the task IAM role.

The Amazon ECS task execution role managed policy (`AmazonECSTaskExecutionRolePolicy`) includes the necessary permissions for pulling images from Amazon ECR. If you're using the managed policy, you don't need to add these permissions separately.

If you're creating a custom policy, include the following permissions to allow pulling images from Amazon ECR:

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

****  

```
{
    "Version":"2012-10-17",		 	 	 
    "Statement": [
        {
            "Effect": "Allow",
            "Action": [
                "ecr:BatchGetImage",
                "ecr:GetDownloadUrlForLayer",
                "ecr:GetAuthorizationToken"
            ],
            "Resource": "*"
        }
    ]
}
```

------

Note that these permissions are different from the permissions that might be required in the task IAM role if your application code needs to interact with Amazon ECR APIs directly. For information about task IAM role permissions for Amazon ECR, see [Amazon ECR permissions](task-iam-roles.md#ecr-required-iam-permissions).

## Amazon S3 file storage permissions


When you specify a configuration file that's hosted in Amazon S3, the task execution role must include the `s3:GetObject` permission for the configuration file and the `s3:GetBucketLocation` permission on the Amazon S3 bucket that the file is in. For more information, see [Policy actions for Amazon S3](https://docs.aws.amazon.com/AmazonS3/latest/userguide/security_iam_service-with-iam.html#security_iam_service-with-iam-id-based-policies-actions) in the *Amazon Simple Storage Service User Guide*.

The following example policy adds the required permissions for retrieving a file from Amazon S3. Specify the name of your Amazon S3 bucket and configuration file name.

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

****  

```
{
  "Version":"2012-10-17",		 	 	 
  "Statement": [
    {
      "Effect": "Allow",
      "Action": [
        "s3:GetObject"
      ],
      "Resource": [
        "arn:aws:s3:::amzn-s3-demo-bucket/folder_name/config_file_name"
      ]
    },
    {
      "Effect": "Allow",
      "Action": [
        "s3:GetBucketLocation"
      ],
      "Resource": [
        "arn:aws:s3:::amzn-s3-demo-bucket"
      ]
    }
  ]
}
```

------

### Important Security Consideration


 When using Amazon ECS features that integrate with Amazon S3 buckets, implement bucket ownership validation to prevent bucket takeover attacks. Without proper validation, if an Amazon S3 bucket is deleted and recreated by a malicious actor with the same name, your tasks may unknowingly load malicious configurations or send sensitive data to attacker-controlled buckets. 

**Recommended IAM Policy Condition:**

```
               "Condition": {
                 "StringEquals": {
                   "aws:ResourceAccount": "TRUSTED-ACCOUNT-ID"
                 }
               }
```

Replace *TRUSTED-ACCOUNT-ID* with the AWS account ID that owns the S3 bucket.

This condition ensures your task execution role can only access Amazon S3 buckets owned by the specified trusted account.

# Amazon ECS task IAM role
Task IAM role

Your Amazon ECS tasks can have an IAM role associated with them. The permissions granted in the IAM role are vended to containers running in the task. This role allows your application code (running in the container) to use other AWS services. The task role is required when your application accesses other AWS services, such as Amazon S3.

**Note**  
These permissions aren't accessed by the Amazon ECS container and Fargate agents. For the IAM permissions that Amazon ECS needs to pull container images and run the task, see [Amazon ECS task execution IAM role](task_execution_IAM_role.md).

The following are the benefits of using task roles:
+ **Separation of concerns**: If you're using EC2, task IAM roles allow you to specify IAM permissions for your containers without requiring these permissions to be specified using EC2 instance profiles (for more information, see [Using instance profiles](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_use_switch-role-ec2_instance-profiles.html) in the *AWS Identity and Access Management User Guide*). Therefore, you can deploy your applications independently and uniformly on ECS container instances without needing to modify IAM permissions associated with EC2 instances.
+ **Auditability**: Access and event logging are available through CloudTrail to ensure retrospective auditing. Task credentials have a context of '`taskArn`' that is attached to the session, so CloudTrail logs show which task the role credentials were vended for.
+ **Uniform credentials delivery**: ECS delivers IAM role credentials to your containers and makes them accessible through a well-defined interface irrespective of the compute option associated with your tasks. On ECS Fargate, EC2 instance profiles are not available for containers in your tasks. Task IAM roles enable you to associate IAM permissions to your containers irrespective of the compute option when you use AWS SDK or AWS CLI in your containers. For more information about how the AWS SDK accesses these credentials, see [Container credential provider](https://docs.aws.amazon.com/sdkref/latest/guide/feature-container-credentials.html).

**Important**  
Containers are not a security boundary and the use of task IAM roles does not change this. Each task running on Fargate has its own isolation boundary and does not share the underlying kernel, CPU resources, memory resources, or elastic network interface with another task. For EC2 and External Container Instances on ECS, there is no task isolation (unlike with Fargate) and containers can potentially access credentials for other tasks on the same container instance. They can also access permissions assigned to the [ECS container instance role](https://docs.aws.amazon.com/AmazonECS/latest/developerguide/instance_IAM_role.html). Follow the recommendations in [Roles recommendations](https://docs.aws.amazon.com/AmazonECS/latest/developerguide/security-iam-roles.html#security-iam-roles-recommendations) to block access to the Amazon EC2 Instance Metadata Service for containers (For more information, see [Use the Instance Metadata Service to access instance metadata](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/configuring-instance-metadata-service.html) in the *Amazon EC2 User Guide*).   
Note that when you specify an IAM role for a task, the AWS CLI or other SDKs in the containers for that task use the AWS credentials provided by the task role exclusively and they do not inherit any IAM permissions from the Amazon EC2 or external instance they are running on.

## Creating the task IAM role


When creating an IAM policy for your tasks to use, the policy must include the permissions that you want the containers in your tasks to assume. You can use an existing AWS managed policy, or you can create a custom policy from scratch that meets your specific needs. For more information, see [Creating IAM policies](https://docs.aws.amazon.com/IAM/latest/UserGuide/access_policies_create.html) in the *IAM User Guide*.

**Important**  
For Amazon ECS tasks (for all launch types), we recommend that you use the IAM policy and role for your tasks. These credentials allow your task to make AWS API requests without calling `sts:AssumeRole` to assume the same role that is already associated with the task. If your task requires that a role assumes itself, you must create a trust policy that explicitly allows that role to assume itself. For more information, see [ Updating a role trust policy](https://docs.aws.amazon.com//IAM/latest/UserGuide/id_roles_update-role-trust-policy.html) in the *IAM User Guide*.

After the IAM policy is created, you can create an IAM role which includes that policy which you reference in your Amazon ECS task definition. You can create the role using the **Elastic Container Service Task** use case in the IAM console. Then, you can attach your specific IAM policy to the role that gives the containers in your task the permissions you desire. The procedures below describe how to do this.

If you have multiple task definitions or services that require IAM permissions, you should consider creating a role for each specific task definition or service with the minimum required permissions for the tasks to operate so that you can minimize the access that you provide for each task. 

For information about the service endpoint for your Region, see [Service endpoints](https://docs.aws.amazon.com/general/latest/gr/ecs-service.html#ecs_region) in the *Amazon Web Services General Reference Guide*.

The IAM task role must have a trust policy that specifies the `ecs-tasks.amazonaws.com` service. The `sts:AssumeRole` permission allows your tasks to assume an IAM role that's different from the one that the Amazon EC2 instance uses. This way, your task doesn't inherit the role associated with the Amazon EC2 instance. The following is an example trust policy. Replace the Region identifier and specify the AWS account number that you use when launching tasks.

**Important**  
When creating your task IAM role, it is recommended that you use the `aws:SourceAccount` or `aws:SourceArn` condition keys in the trust relationship policy associated with the role to scope the permissions further to prevent the confused deputy security issue. Using the `aws:SourceArn` condition key to specify a specific cluster is not currently supported, you should use the wildcard to specify all clusters. To learn more about the confused deputy problem and how to protect your AWS account, see [The confused deputy problem](https://docs.aws.amazon.com/IAM/latest/UserGuide/confused-deputy.html) in the *IAM User Guide*.

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

****  

```
{
   "Version":"2012-10-17",		 	 	 
   "Statement":[
      {
         "Effect":"Allow",
         "Principal":{
            "Service":[
               "ecs-tasks.amazonaws.com"
            ]
         },
         "Action":"sts:AssumeRole",
         "Condition":{
            "ArnLike":{
            "aws:SourceArn":"arn:aws:ecs:us-west-2:111122223333:*"
            },
            "StringEquals":{
               "aws:SourceAccount":"111122223333"
            }
         }
      }
   ]
}
```

------

Use the following procedure to create a policy to retrieve objects from Amazon S3 with an example policy. Replace all *user input* with your own values.

------
#### [ AWS Management Console ]

**To use the JSON policy editor to create a policy**

1. Sign in to the AWS Management Console and open the IAM console at [https://console.aws.amazon.com/iam/](https://console.aws.amazon.com/iam/).

1. In the navigation pane on the left, choose **Policies**. 

   If this is your first time choosing **Policies**, the **Welcome to Managed Policies** page appears. Choose **Get Started**.

1. At the top of the page, choose **Create policy**.

1. In the **Policy editor** section, choose the **JSON** option.

1. Enter the following JSON policy document:

   ```
   {
      "Version":"2012-10-17",		 	 	 
      "Statement":[
         {
            "Effect":"Allow",
            "Action":[
               "s3:GetObject"
            ],
            "Resource":[
               "arn:aws:s3:::my-task-secrets-bucket/*"
            ]
         }
      ]
   }
   ```

1. Choose **Next**.
**Note**  
You can switch between the **Visual** and **JSON** editor options anytime. However, if you make changes or choose **Next** in the **Visual** editor, IAM might restructure your policy to optimize it for the visual editor. For more information, see [Policy restructuring](https://docs.aws.amazon.com/IAM/latest/UserGuide/troubleshoot_policies.html#troubleshoot_viseditor-restructure) in the *IAM User Guide*.

1. On the **Review and create** page, enter a **Policy name** and a **Description** (optional) for the policy that you are creating. Review **Permissions defined in this policy** to see the permissions that are granted by your policy.

1. Choose **Create policy** to save your new policy.

------
#### [ AWS CLI ]

Replace all *user input* with your own values.

1. Create a file called `s3-policy.json` with the following content.

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

****  

   ```
   {
      "Version":"2012-10-17",		 	 	 
      "Statement":[
         {
            "Effect":"Allow",
            "Action":[
               "s3:GetObject"
            ],
            "Resource":[
               "arn:aws:s3:::my-task-secrets-bucket/*"
            ]
         }
      ]
   }
   ```

------

1. Use the following command to create the IAM policy using the JSON policy document file. Replace all *user input* with your own values.

   ```
   aws iam create-policy \
         --policy-name taskRolePolicy \
         --policy-document file://s3-policy.json
   ```

------

Use the following procedure to create the service role.

------
#### [ AWS Management Console ]

**To create the service role for Elastic Container Service (IAM console)**

1. Sign in to the AWS Management Console and open the IAM console at [https://console.aws.amazon.com/iam/](https://console.aws.amazon.com/iam/).

1. In the navigation pane of the IAM console, choose **Roles**, and then choose **Create role**.

1. For **Trusted entity type**, choose **AWS service**.

1. For **Service or use case**, choose **Elastic Container Service**, and then choose the **Elastic Container Service Task** use case.

1. Choose **Next**.

1. For **Add permissions**, search for and choose the policy you created.

1. Choose **Next**.

1. For **Role name**, enter a name for your role. For this example, type `AmazonECSTaskS3BucketRole` to name the role.

1. Review the role, and then choose **Create role**.

------
#### [ AWS CLI ]

1. Create a file named `ecs-tasks-trust-policy.json` that contains the trust policy to use for the task IAM role. The file should contain the following. Replace the Region identifier and specify the AWS account number that you use when launching tasks.

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

****  

   ```
   {
      "Version":"2012-10-17",		 	 	 
      "Statement":[
         {
            "Effect":"Allow",
            "Principal":{
               "Service":[
                  "ecs-tasks.amazonaws.com"
               ]
            },
            "Action":"sts:AssumeRole",
            "Condition":{
               "ArnLike":{
               "aws:SourceArn":"arn:aws:ecs:us-west-2:111122223333:*"
               },
               "StringEquals":{
                  "aws:SourceAccount":"111122223333"
               }
            }
         }
      ]
   }
   ```

------

1. Create an IAM role named `ecsTaskRole` using the trust policy created in the previous step.

   ```
   aws iam create-role \
         --role-name ecsTaskRole \
         --assume-role-policy-document file://ecs-tasks-trust-policy.json
   ```

1. Retrieve the ARN of the IAM policy you created using the following command. Replace *taskRolePolicy* with the name of the policy you created.

   ```
   aws iam list-policies --scope Local --query 'Policies[?PolicyName==`taskRolePolicy`].Arn'
   ```

1. Attach the IAM policy you created to the `ecsTaskRole` role. Replace the `policy-arn` with the ARN of the policy that you created.

   ```
   aws iam attach-role-policy \
         --role-name ecsTaskRole \
         --policy-arn arn:aws:iam:111122223333:aws:policy/taskRolePolicy
   ```

------

After you create the role, add additional permissions to the role for the following features.


|  Feature  |  Additional permissions  | 
| --- | --- | 
|  Use ECS Exec  |  [ECS Exec permissions](#ecs-exec-required-iam-permissions)  | 
| Use an image from a private Amazon ECR repository | [Amazon ECR permissions](#ecr-required-iam-permissions) | 
| Use EC2 instances (Windows and Linux) | [Amazon EC2 instances additional configuration](#task-iam-role-considerations) | 
| Use external instances | [External instance additional configuration](#enable_task_iam_roles) | 
| Use Windows EC2 instances | [Amazon EC2 Windows instance additional configuration](#windows_task_IAM_roles) | 

## Amazon ECR permissions


The following permissions are required when your application code needs to interact with Amazon ECR repositories directly. Note that for basic implementation where you only need to pull images from Amazon ECR, these permissions are not required at the task IAM role level. Instead, the Amazon ECS task execution role should have these permissions. For more information about the task execution role, see [Amazon ECS task execution IAM role](task_execution_IAM_role.md).

If your application code running in the container needs to interact with Amazon ECR APIs directly, you should add the following permissions to a task IAM role and include the task IAM role in your task definition. For more information, see [Adding and Removing IAM Policies](https://docs.aws.amazon.com/IAM/latest/UserGuide/access_policies_manage-attach-detach.html) in the *IAM User Guide*.

Use the following policy for your task IAM role to add the required Amazon ECR permissions for container applications that need to interact with Amazon ECR directly: 

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

****  

```
{
    "Version":"2012-10-17",		 	 	 
    "Statement": [
        {
            "Effect": "Allow",
            "Action": [
                "ecr:BatchGetImage",
                "ecr:GetDownloadUrlForLayer",
                "ecr:GetAuthorizationToken"
            ],
            "Resource": "*"
        }
    ]
}
```

------

## ECS Exec permissions


The [ECS Exec](https://docs.aws.amazon.com/AmazonECS/latest/developerguide/ecs-exec.html) feature requires a task IAM role to grant containers the permissions needed for communication between the managed SSM agent (`execute-command` agent) and the SSM service. You should add the following permissions to a task IAM role and include the task IAM role in your task definition. For more information, see [Adding and Removing IAM Policies](https://docs.aws.amazon.com/IAM/latest/UserGuide/access_policies_manage-attach-detach.html) in the *IAM User Guide*.

Use the following policy for your task IAM role to add the required SSM permissions. 

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

****  

```
{
   "Version":"2012-10-17",		 	 	 
   "Statement": [
       {
       "Effect": "Allow",
       "Action": [
            "ssmmessages:CreateControlChannel",
            "ssmmessages:CreateDataChannel",
            "ssmmessages:OpenControlChannel",
            "ssmmessages:OpenDataChannel"
       ],
      "Resource": "*"
      }
   ]
}
```

------

## Amazon EC2 instances additional configuration


We recommend that you limit the permissions in your container instance role to the minimal list of permissions used in the `AmazonEC2ContainerServiceforEC2Role` managed IAM policy. 

Your Amazon EC2 instances require at least version `1.11.0` of the container agent to use task role; however, we recommend using the latest container agent version. For information about checking your agent version and updating to the latest version, see [Updating the Amazon ECS container agent](ecs-agent-update.md). If you use an Amazon ECS-optimized AMI, your instance needs at least `1.11.0-1` of the `ecs-init` package. If your instances are using the latest Amazon ECS-optimized AMI, then they contain the required versions of the container agent and `ecs-init`. For more information, see [Amazon ECS-optimized Linux AMIs](ecs-optimized_AMI.md).

If you are not using the Amazon ECS-optimized AMI for your container instances, add the `--net=host` option to your **docker run** command that starts the agent and the following agent configuration variables for your desired configuration (for more information, see [Amazon ECS container agent configuration](ecs-agent-config.md)):

`ECS_ENABLE_TASK_IAM_ROLE=true`  
Uses IAM roles for tasks for containers with the `bridge` and `default` network modes.

`ECS_ENABLE_TASK_IAM_ROLE_NETWORK_HOST=true`  
Uses IAM roles for tasks for containers with the `host` network mode. This variable is only supported on agent versions 1.12.0 and later.

For an example run command, see [Manually updating the Amazon ECS container agent (for non-Amazon ECS-Optimized AMIs)](manually_update_agent.md). You will also need to set the following networking commands on your container instance so that the containers in your tasks can retrieve their AWS credentials:

```
sudo sysctl -w net.ipv4.conf.all.route_localnet=1
sudo iptables -t nat -A PREROUTING -p tcp -d 169.254.170.2 --dport 80 -j DNAT --to-destination 127.0.0.1:51679
sudo iptables -t nat -A OUTPUT -d 169.254.170.2 -p tcp -m tcp --dport 80 -j REDIRECT --to-ports 51679
```

You must save these **iptables** rules on your container instance for them to survive a reboot. You can use the **iptables-save** and **iptables-restore** commands to save your **iptables** rules and restore them at boot. For more information, consult your specific operating system documentation.

To prevent containers run by tasks that use the `awsvpc` network mode from accessing the credential information supplied to the Amazon EC2 instance profile, while still allowing the permissions that are provided by the task role, set the `ECS_AWSVPC_BLOCK_IMDS` agent configuration variable to `true` in the agent configuration file and restart the agent. For more information, see [Amazon ECS container agent configuration](ecs-agent-config.md).

To prevent containers run by tasks that use the `bridge` network mode from accessing the credential information supplied to the Amazon EC2 instance profile, while still allowing the permissions that are provided by the task role, by running the following **iptables** command on your Amazon EC2 instances. This command doesn't affect containers in tasks that use the `host` or `awsvpc` network modes. For more information, see [Network mode](task_definition_parameters.md#network_mode).
+ 

  ```
  sudo yum install -y iptables-services; sudo iptables --insert DOCKER-USER 1 --in-interface docker+ --destination 169.254.169.254/32 --jump DROP
  ```

  You must save this **iptables** rule on your Amazon EC2 instance for it to survive a reboot. When using the Amazon ECS-optimized AMI, you can use the following command. For other operating systems, consult the documentation for that operating system.

  ```
  sudo iptables-save | sudo tee /etc/sysconfig/iptables && sudo systemctl enable --now iptables
  ```

## External instance additional configuration


Your external instances require at least version `1.11.0` of the container agent to use task IAM roles; however, we recommend using the latest container agent version. For information about checking your agent version and updating to the latest version, see [Updating the Amazon ECS container agent](ecs-agent-update.md). If you are using an Amazon ECS-optimized AMI, your instance needs at least `1.11.0-1` of the `ecs-init` package. If your instances are using the latest Amazon ECS-optimized AMI, then they contain the required versions of the container agent and `ecs-init`. For more information, see [Amazon ECS-optimized Linux AMIs](ecs-optimized_AMI.md).

If you are not using the Amazon ECS-optimized AMI for your container instances, add the `--net=host` option to your **docker run** command that starts the agent and the following agent configuration variables for your desired configuration (for more information, see [Amazon ECS container agent configuration](ecs-agent-config.md)):

`ECS_ENABLE_TASK_IAM_ROLE=true`  
Uses IAM roles for tasks for containers with the `bridge` and `default` network modes.

`ECS_ENABLE_TASK_IAM_ROLE_NETWORK_HOST=true`  
Uses IAM roles for tasks for containers with the `host` network mode. This variable is only supported on agent versions 1.12.0 and later.

For an example run command, see [Manually updating the Amazon ECS container agent (for non-Amazon ECS-Optimized AMIs)](manually_update_agent.md). You will also need to set the following networking commands on your container instance so that the containers in your tasks can retrieve their AWS credentials:

```
sudo sysctl -w net.ipv4.conf.all.route_localnet=1
sudo iptables -t nat -A PREROUTING -p tcp -d 169.254.170.2 --dport 80 -j DNAT --to-destination 127.0.0.1:51679
sudo iptables -t nat -A OUTPUT -d 169.254.170.2 -p tcp -m tcp --dport 80 -j REDIRECT --to-ports 51679
```

You must save these **iptables** rules on your container instance for them to survive a reboot. You can use the **iptables-save** and **iptables-restore** commands to save your **iptables** rules and restore them at boot. For more information, consult your specific operating system documentation.

## Amazon EC2 Windows instance additional configuration


**Important**  
This applies only to Windows containers on EC2 that use task roles.

The task role with Windows features requires additional configuration on EC2.
+ When you launch your container instances, you must set the `-EnableTaskIAMRole` option in the container instances user data script. The `EnableTaskIAMRole` turns on the Task IAM roles feature for the tasks. For example:

  ```
  <powershell>
  Import-Module ECSTools
  Initialize-ECSAgent -Cluster 'windows' -EnableTaskIAMRole 
  </powershell>
  ```
+ You must bootstrap your container with the networking commands that are provided in [Amazon ECS container bootstrap script](#windows_task_IAM_roles_bootstrap).
+ You must create an IAM role and policy for your tasks. For more information, see [Creating the task IAM role](#create_task_iam_policy_and_role).
+ The IAM roles for the task credential provider use port 80 on the container instance. Therefore, if you configure IAM roles for tasks on your container instance, your containers can't use port 80 for the host port in any port mappings. To expose your containers on port 80, we recommend configuring a service for them that uses load balancing. You can use port 80 on the load balancer. By doing so, traffic can be routed to another host port on your container instances. For more information, see [Use load balancing to distribute Amazon ECS service traffic](service-load-balancing.md).
+ If your Windows instance is restarted, you must delete the proxy interface and initialize the Amazon ECS container agent again to bring the credential proxy back up.

### Amazon ECS container bootstrap script


Before containers can access the credential proxy on the container instance to get credentials, the container must be bootstrapped with the required networking commands. The following code example script should be run on your containers when they start.

**Note**  
You do not need to run this script when you use `awsvpc` network mode on Windows.

If you run Windows containers which include Powershell, then use the following script:

```
# Copyright Amazon.com Inc. or its affiliates. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"). You may
# not use this file except in compliance with the License. A copy of the
# License is located at
#
#	http://aws.amazon.com/apache2.0/
#
# or in the "license" file accompanying this file. This file is distributed
# on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
# express or implied. See the License for the specific language governing
# permissions and limitations under the License.
 
$gateway = (Get-NetRoute | Where { $_.DestinationPrefix -eq '0.0.0.0/0' } | Sort-Object RouteMetric | Select NextHop).NextHop
$ifIndex = (Get-NetAdapter -InterfaceDescription "Hyper-V Virtual Ethernet*" | Sort-Object | Select ifIndex).ifIndex
New-NetRoute -DestinationPrefix 169.254.170.2/32 -InterfaceIndex $ifIndex -NextHop $gateway -PolicyStore ActiveStore # credentials API
New-NetRoute -DestinationPrefix 169.254.169.254/32 -InterfaceIndex $ifIndex -NextHop $gateway -PolicyStore ActiveStore # metadata API
```

If you run Windows containers that only have the Command shell, then use the following script:

```
# Copyright Amazon.com Inc. or its affiliates. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"). You may
# not use this file except in compliance with the License. A copy of the
# License is located at
#
#	http://aws.amazon.com/apache2.0/
#
# or in the "license" file accompanying this file. This file is distributed
# on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
# express or implied. See the License for the specific language governing
# permissions and limitations under the License.
 
for /f "tokens=1" %i  in ('netsh interface ipv4 show interfaces ^| findstr /x /r ".*vEthernet.*"') do set interface=%i
for /f "tokens=3" %i  in ('netsh interface ipv4 show addresses %interface% ^| findstr /x /r ".*Default.Gateway.*"') do set gateway=%i
netsh interface ipv4 add route prefix=169.254.170.2/32 interface="%interface%" nexthop="%gateway%" store=active # credentials API
netsh interface ipv4 add route prefix=169.254.169.254/32 interface="%interface%" nexthop="%gateway%" store=active # metadata API
```

# Amazon ECS container instance IAM role
Container instance IAM role

Amazon ECS container instances, including both Amazon EC2 and external instances, run the Amazon ECS container agent and require an IAM role for the service to know that the agent belongs to you. Before you launch container instances and register them to a cluster, you must create an IAM role for your container instances to use. The role is created in the account that you use to log into the console or run the AWS CLI commands.

**Important**  
If you are registering external instances to your cluster, the IAM role you use requires Systems Manager permissions as well. For more information, see [Amazon ECS Anywhere IAM role](iam-role-ecsanywhere.md).

Amazon ECS provides the `AmazonEC2ContainerServiceforEC2Role` managed IAM policy which contains the permissions needed to use the full Amazon ECS feature set. This managed policy can be attached to an IAM role and associated with your container instances. Alternatively, you can use the managed policy as a guide when creating a custom policy to use. The container instance role provides permissions needed for the Amazon ECS container agent and Docker daemon to call AWS APIs on your behalf. For more information on the managed policy, see [AmazonEC2ContainerServiceforEC2Role](security-iam-awsmanpol.md#security-iam-awsmanpol-AmazonEC2ContainerServiceforEC2Role).

## Create the container instance role


**Important**  
If you are registering external instances to your cluster, see [Amazon ECS Anywhere IAM role](iam-role-ecsanywhere.md).

You can manually create the role and attach the managed IAM policy for container instances to allow Amazon ECS to add permissions for future features and enhancements as they are introduced. Use the following procedure to attach the managed IAM policy if needed.

------
#### [ AWS Management Console ]

**To create the service role for Elastic Container Service (IAM console)**

1. Sign in to the AWS Management Console and open the IAM console at [https://console.aws.amazon.com/iam/](https://console.aws.amazon.com/iam/).

1. In the navigation pane of the IAM console, choose **Roles**, and then choose **Create role**.

1. For **Trusted entity type**, choose **AWS service**.

1. For **Service or use case**, choose **Elastic Container Service**, and then choose the **EC2 Role for Elastic Container Service** use case.

1. Choose **Next**.

1. In the **Permissions policies** section, verify that the **AmazonEC2ContainerServiceforEC2Role** policy is selected.
**Important**  
The **AmazonEC2ContainerServiceforEC2Role** managed policy should be attached to the container instance IAM role, otherwise you will receive an error using the AWS Management Console to create clusters.

1. Choose **Next**.

1.  For **Role name**, enter **ecsInstanceRole**

1. Review the role, and then choose **Create role**.

------
#### [ AWS CLI ]

Replace all *user input* with your own values.

1. Create a file called `instance-role-trust-policy.json` with the following contents.  
****  

   ```
   {
     "Version":"2012-10-17",		 	 	 
     "Statement": [
       {
         "Effect": "Allow",
         "Principal": { "Service": "ec2.amazonaws.com"},
         "Action": "sts:AssumeRole"
       }
     ]
   }
   ```

1. Use the following command to create the instance IAM role using the trust policy document.

   ```
   aws iam create-role \
       --role-name ecsInstanceRole \
       --assume-role-policy-document file://instance-role-trust-policy.json
   ```

1. Create an instance profile named `ecsInstanceRole-profile` using the [create-instance-profile](https://docs.aws.amazon.com/cli/latest/reference/iam/create-instance-profile.html) command. 

   ```
   aws iam create-instance-profile --instance-profile-name ecsInstanceRole-profile
   ```

   Example response

   ```
   {
       "InstanceProfile": {
           "InstanceProfileId": "AIPAJTLBPJLEGREXAMPLE",
           "Roles": [],
           "CreateDate": "2022-04-12T23:53:34.093Z",
           "InstanceProfileName": "ecsInstanceRole-profile",
           "Path": "/",
           "Arn": "arn:aws:iam::123456789012:instance-profile/ecsInstanceRole-profile"
       }
   }
   ```

1. Add the `ecsInstanceRole` role to the `ecsInstanceRole-profile` instance profile.

   ```
   aws iam add-role-to-instance-profile \
       --instance-profile-name ecsInstanceRole-profile \
       --role-name ecsInstanceRole
   ```

1. Attach the `AmazonEC2ContainerServiceForEC2Role` managed policy to the role using the following command.

   ```
   aws iam attach-role-policy \
       --policy-arn arn:aws:iam::aws:policy/service-role/AmazonEC2ContainerServiceforEC2Role \
       --role-name ecsInstanceRole
   ```

------

After you create the role, add additional permissions to the role for the following features.


|  Feature  |  Additional permissions  | 
| --- | --- | 
|  Amazon ECR has the container image  |  [Amazon ECR permissions](#container-instance-role-ecr)  | 
| Have CloudWatch Logs monitor container instances | [Monitoring container instances permissions](#cwl_iam_policy) | 
| Host configuration files in an Amazon S3 bucket | [Amazon S3 read-only access](#container-instance-role-s3) | 

## Amazon ECR permissions


The Amazon ECS container instance role that you use with your container instances must have the following IAM policy permissions for Amazon ECR.

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

****  

```
{
    "Version":"2012-10-17",		 	 	 
    "Statement": [
        {
            "Effect": "Allow",
            "Action": [
                "ecr:BatchCheckLayerAvailability",
                "ecr:BatchGetImage",
                "ecr:GetDownloadUrlForLayer",
                "ecr:GetAuthorizationToken"
            ],
            "Resource": "*"
        }
    ]
}
```

------

If you use the `AmazonEC2ContainerServiceforEC2Role` managed policy for your container instances, then your role has the proper permissions.

## Permissions required for setting the awsvpcTrunking account setting


Amazon ECS supports launching container instances with increased ENI density using supported Amazon EC2 instance types. When you use this feature, we recommend that you create 2 container instance roles. Enable the `awsvpcTrunking` account setting for one role and use that role for tasks that require ENI trunking. For information about the `awsvpcTrunking` account setting, see [Access Amazon ECS features with account settings](ecs-account-settings.md).

The container instance role that you use with your container instances must have the following IAM policy permissions for setting the account setting 

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

****  

```
{
    "Version":"2012-10-17",		 	 	 
    "Statement": [
        {
            "Effect": "Allow",
            "Action": [
                "ecs:ListAccountSettings", 
                "ecs:ListAttributes", 
                "ecs:PutAccountSetting" 
            ],
            "Resource": "*"
        }
    ]
}
```

------

In order to use the container instance role, add the following to instance user data:

```
#!/bin/bash
aws ecs put-account-setting --name awsvpcTrunking --value enabled --region region
ECS_CLUSTER=MyCluster>> /etc/ecs/ecs.config
EOF
```

For more information about adding user data to your EC2 instances, see [Run commands on your Linux instance at launch](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/user-data.html) in the *Amazon EC2 User Guide*.

## Amazon S3 read-only access


Storing configuration information in a private bucket in Amazon S3 and granting read-only access to your container instance IAM role is a secure and convenient way to allow container instance configuration at launch time. You can store a copy of your `ecs.config` file in a private bucket, use Amazon EC2 user data to install the AWS CLI and then copy your configuration information to `/etc/ecs/ecs.config` when the instance launches.

For more information about creating an `ecs.config` file, storing it in Amazon S3, and launching instances with this configuration, see [Storing Amazon ECS container instance configuration in Amazon S3](ecs-config-s3.md).

You can use the following AWS CLI command to allow Amazon S3 read-only access for your container instance role. Replace *ecsInstanceRole* with the name of the role that you created.

```
aws iam attach-role-policy \
      --role-name ecsInstanceRole \
      --policy-arn arn:aws:iam::aws:policy/AmazonS3ReadOnlyAccess
```

You can also use the IAM console to add Amazon S3 read-only access (`AmazonS3ReadOnlyAccess`) to your role. For more information, see [Updating permissions for a role](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_update-role-permissions.html) in the *AWS Identity and Access Management User Guide*.

## Monitoring container instances permissions


Before your container instances can send log data to CloudWatch Logs, you must create an IAM policy to allow the Amazon ECS agent to write the customer's application logs to CloudWatch (normally handled through the `awslogs` driver). After you create the policy, attach that policy to `ecsInstanceRole`.

------
#### [ AWS Management Console ]

**To use the JSON policy editor to create a policy**

1. Sign in to the AWS Management Console and open the IAM console at [https://console.aws.amazon.com/iam/](https://console.aws.amazon.com/iam/).

1. In the navigation pane on the left, choose **Policies**. 

   If this is your first time choosing **Policies**, the **Welcome to Managed Policies** page appears. Choose **Get Started**.

1. At the top of the page, choose **Create policy**.

1. In the **Policy editor** section, choose the **JSON** option.

1. Enter the following JSON policy document:

   ```
   {
       "Version": "2012-10-17",		 	 	 
       "Statement": [
           {
               "Effect": "Allow",
               "Action": [
                   "logs:CreateLogGroup",
                   "logs:CreateLogStream",
                   "logs:PutLogEvents",
                   "logs:DescribeLogStreams"
               ],
               "Resource": ["arn:aws:logs:*:*:*"]
           }
       ]
   }
   ```

1. Choose **Next**.
**Note**  
You can switch between the **Visual** and **JSON** editor options anytime. However, if you make changes or choose **Next** in the **Visual** editor, IAM might restructure your policy to optimize it for the visual editor. For more information, see [Policy restructuring](https://docs.aws.amazon.com/IAM/latest/UserGuide/troubleshoot_policies.html#troubleshoot_viseditor-restructure) in the *IAM User Guide*.

1. On the **Review and create** page, enter a **Policy name** and a **Description** (optional) for the policy that you are creating. Review **Permissions defined in this policy** to see the permissions that are granted by your policy.

1. Choose **Create policy** to save your new policy.

After you create the policy, attach the policy to the container instance role. For information about how to attach the policy to the role, see [Updating permissions for a role](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_update-role-permissions.html) in the *AWS Identity and Access Management User Guide*.

------
#### [ AWS CLI ]

1. Create a file called `instance-cw-logs.json` with the following content.  
****  

   ```
   {
       "Version":"2012-10-17",		 	 	 
       "Statement": [
           {
               "Effect": "Allow",
               "Action": [
                   "logs:CreateLogGroup",
                   "logs:CreateLogStream",
                   "logs:PutLogEvents",
                   "logs:DescribeLogStreams"
               ],
               "Resource": ["arn:aws:logs:*:*:*"]
           }
       ]
   }
   ```

1. Use the following command to create the IAM policy using the JSON policy document file.

   ```
   aws iam create-policy \
         --policy-name cwlogspolicy \
         --policy-document file://instance-cw-logs.json
   ```

1. Retrieve the ARN of the IAM policy you created using the following command. Replace *cwlogspolicy* with the name of the policy you created.

   ```
   aws iam list-policies --scope Local --query 'Policies[?PolicyName==`cwlogspolicy`].Arn'
   ```

1. Use the following command to attach the policy to the container instance IAM role using the policy ARN.

   ```
   aws iam attach-role-policy \
         --role-name ecsInstanceRole \
         --policy-arn arn:aws:iam:111122223333:aws:policy/cwlogspolicy
   ```

------

# Amazon ECS Anywhere IAM role


When you register an on-premises server or virtual machine (VM) to your cluster, the server or VM requires an IAM role to communicate with AWS APIs. You only need to create this IAM role once for each AWS account. However, this IAM role must be associated with each server or VM that you register to a cluster. This role is the `ECSAnywhereRole`. You can create this role manually. Alternatively, Amazon ECS can create the role on your behalf when you register an external instance in the AWS Management Console. You can use IAM console search to search for `ecsAnywhereRole` and see if your account already has the role. For more information, see [IAM console search](https://docs.aws.amazon.com/IAM/latest/UserGuide/console_search.html) in the *IAM user guide*.

AWS provides two managed IAM policies that can be used when creating the ECS Anywhere IAM role, the `AmazonSSMManagedInstanceCore` and `AmazonEC2ContainerServiceforEC2Role` policies. The `AmazonEC2ContainerServiceforEC2Role` policy includes permissions that likely provide more access than you need. Therefore, depending on your specific use case, we recommend that you create a custom policy adding only the permissions from that policy that you require in it. For more information, see [Amazon ECS container instance IAM role](instance_IAM_role.md).

The task execution IAM role grants the Amazon ECS container agent permission to make AWS API calls on your behalf. When a task execution IAM role is used, it must be specified in your task definition. For more information, see [Amazon ECS task execution IAM role](task_execution_IAM_role.md).

The task execution role is required if any of the following conditions apply:
+ You're sending container logs to CloudWatch Logs using the `awslogs` log driver.
+ Your task definition specifies a container image that's hosted in an Amazon ECR private repository. However, if the `ECSAnywhereRole` role that's associated with your external instance also includes the permissions necessary to pull images from Amazon ECR then your task execution role doesn't need to include them.

## Creating the Amazon ECS Anywhere role


Replace all *user input* with your own information.

1. Create a local file named `ssm-trust-policy.json` with the following trust policy.

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

****  

   ```
   {
     "Version":"2012-10-17",		 	 	 
     "Statement": {
       "Effect": "Allow",
       "Principal": {"Service": [
         "ssm.amazonaws.com"
       ]},
       "Action": "sts:AssumeRole"
     }
   }
   ```

------

1. Create the role and attach the trust policy by using the following AWS CLI command.

   ```
   aws iam create-role --role-name ecsAnywhereRole --assume-role-policy-document file://ssm-trust-policy.json
   ```

1. Attach the AWS managed policies by using the following command.

   ```
   aws iam attach-role-policy --role-name ecsAnywhereRole --policy-arn arn:aws:iam::aws:policy/AmazonSSMManagedInstanceCore
   aws iam attach-role-policy --role-name ecsAnywhereRole --policy-arn arn:aws:iam::aws:policy/service-role/AmazonEC2ContainerServiceforEC2Role
   ```

You can also use the IAM custom trust policy workflow to create the role. For more information, see [Creating a role using custom trust policies (console)](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_create_for-custom.html) in the *IAM User Guide*.

# Amazon ECS infrastructure IAM role
Infrastructure IAM role

An Amazon ECS infrastructure IAM role allows Amazon ECS to manage infrastructure resources in your clusters on your behalf, and is used when:
+ You want to attach Amazon EBS volumes to your Fargate or EC2 launch type Amazon ECS tasks. The infrastructure role allows Amazon ECS to manage Amazon EBS volumes for your tasks.

  You can use the `AmazonECSInfrastructureRolePolicyForVolumes` managed policy.
+ You want to use Transport Layer Security (TLS) to encrypt traffic between your Amazon ECS Service Connect services.

  You can use the `AmazonECSInfrastructureRolePolicyForServiceConnectTransportLayerSecurity` managed policy.
+ You want to create Amazon VPC Lattice target groups.

  You can use the `AmazonECSInfrastructureRolePolicyForVpcLattice` managed policy.
+ You want to use Amazon ECS Managed Instances in your Amazon ECS clusters. The infrastructure role allows Amazon ECS to manage the lifecycle of managed instances.

  You can use the `AmazonECSInfrastructureRolePolicyForManagedInstances` managed policy.
+ You want to use Express Mode. The infrastructure role allows Amazon ECS to provision and manage the infrastructure components required for Express Mode services, including load balancing, security groups, SSL certificates, and auto scaling configurations.

  You can use the `AmazonECSInfrastructureRoleforExpressGatewayServices` managed policy.

 When Amazon ECS assumes this role to take actions on your behalf, the events will be visible in AWS CloudTrail. If Amazon ECS uses the role to manage Amazon EBS volumes attached to your tasks, the CloudTrail log `roleSessionName` will be `ECSTaskVolumesForEBS`. If the role is used to encrypt traffic between your Service Connect services, the CloudTrail log `roleSessionName` will be `ECSServiceConnectForTLS`. If the role is used to create target groups for VPC Lattice, the CloudTrail log `roleSessionName` will be `ECSNetworkingWithVPCLattice`. If the role is used to manage Amazon ECS Managed Instances, the CloudTrail log `roleSessionName` will be `ECSManagedInstancesForCompute`. You can use this name to search events in the CloudTrail console by filtering for **User name**.

Amazon ECS provides managed policies which contain the permissions required for volume attachment, TLS, VPC Lattice, and managed instances. For more information see, [AmazonECSInfrastructureRolePolicyForVolumes](https://docs.aws.amazon.com/aws-managed-policy/latest/reference/AmazonECSInfrastructureRolePolicyForVolumes.html), [AmazonECSInfrastructureRolePolicyForServiceConnectTransportLayerSecurity](https://docs.aws.amazon.com/aws-managed-policy/latest/reference/AmazonECSInfrastructureRolePolicyForServiceConnectTransportLayerSecurity.html), [AmazonECSInfrastructureRolePolicyForVpcLattice](https://docs.aws.amazon.com/aws-managed-policy/latest/reference/AmazonECSInfrastructureRolePolicyForVpcLattice.html), [AmazonECSInfrastructureRolePolicyForManagedInstances](https://docs.aws.amazon.com/aws-managed-policy/latest/reference/AmazonECSInfrastructureRolePolicyForManagedInstances.html), and [AmazonECSInfrastructureRoleforExpressGatewayServices](https://docs.aws.amazon.com/aws-managed-policy/latest/reference/AmazonECSInfrastructureRoleforExpressGatewayServices.html) in the *AWS Managed Policy Reference Guide*. 

## Creating the Amazon ECS infrastructure role


Replace all *user input* with your own information.

1. Create a file named `ecs-infrastructure-trust-policy.json` that contains the trust policy to use for the IAM role. The file should contain the following:

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

****  

   ```
   {
     "Version":"2012-10-17",		 	 	  
     "Statement": [ 
       {
         "Sid": "AllowAccessToECSForInfrastructureManagement", 
         "Effect": "Allow", 
         "Principal": {
           "Service": "ecs.amazonaws.com" 
         }, 
         "Action": "sts:AssumeRole" 
       } 
     ] 
   }
   ```

------

1. Use the following AWS CLI command to create a role named `ecsInfrastructureRole` by using the trust policy that you created in the previous step.

   ```
   aws iam create-role \
         --role-name ecsInfrastructureRole \
         --assume-role-policy-document file://ecs-infrastructure-trust-policy.json
   ```

1. Depending on your use case, attach the managed policy to the `ecsInfrastructureRole` role.
   + To attach Amazon EBS volumes to your Fargate or EC2 launch type Amazon ECS tasks, attach the `AmazonECSInfrastructureRolePolicyForVolumes` managed policy.
   + To use Transport Layer Security (TLS) to encrypt traffic between your Amazon ECS Service Connect services, attach the `AmazonECSInfrastructureRolePolicyForServiceConnectTransportLayerSecurity` managed policy.
   + To create Amazon VPC Lattice target groups, attach the `AmazonECSInfrastructureRolePolicyForVpcLattice` managed policy.
   + You want to use Amazon ECS Managed Instances in your Amazon ECS clusters, attach the `AmazonECSInfrastructureRolePolicyForManagedInstances` managed policy.

   ```
   aws iam attach-role-policy \
         --role-name ecsInfrastructureRole \
         --policy-arn arn:aws:iam::aws:policy/service-role/AmazonECSInfrastructureRolePolicyForVolumes
   ```

   ```
   aws iam attach-role-policy \
         --role-name ecsInfrastructureRole \
         --policy-arn arn:aws:iam::aws:policy/service-role/AmazonECSInfrastructureRolePolicyForServiceConnectTransportLayerSecurity
   ```

   ```
   aws iam attach-role-policy \
         --role-name ecsInfrastructureRole \
         --policy-arn arn:aws:iam::aws:policy/AmazonECSInfrastructureRolePolicyForManagedInstances
   ```

You can also use the IAM console's **Custom trust policy** workflow to create the role. For more information, see [Creating a role using custom trust policies (console)](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_create_for-custom.html) in the *IAM User Guide*.

**Important**  
If the infrastructure role is being used by Amazon ECS to manage Amazon EBS volumes attached to your tasks, ensure the following before you stop tasks that use Amazon EBS volumes.  
The role isn't deleted.
The trust policy for the role isn't modified to remove Amazon ECS access (`ecs.amazonaws.com`).
The managed policy `AmazonECSInfrastructureRolePolicyForVolumes` isn't removed. If you must modify the role's permissions, retain at least `ec2:DetachVolume`, `ec2:DeleteVolume`, and `ec2:DescribeVolumes` for volume deletion.
Deleting or modifying the role before stopping tasks with attached Amazon EBS volumes will result in the tasks getting stuck in `DEPROVISIONING` and the associated Amazon EBS volumes failing to delete. Amazon ECS will automatically retry at regular intervals to stop the task and delete the volume until the necessary permissions are restored. You can view a task's volume attachment status and associated status reason by using the [DescribeTasks](https://docs.aws.amazon.com/AmazonECS/latest/APIReference/API_DescribeTasks.html) API.

After you create the file, you must grant your user permission to pass the role to Amazon ECS.

## Permission to pass the infrastructure role to Amazon ECS


To use an ECS infrastructure IAM role, you must grant your user permission to pass the role to Amazon ECS. Attach the following `iam:PassRole` permission to your user. Replace *ecsInfrastructureRole* with the name of the infrastructure role that you created.

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

****  

```
{
    "Version":"2012-10-17",		 	 	 
    "Statement": [
    
        {
            "Action": "iam:PassRole",
            "Effect": "Allow",
            "Resource": ["arn:aws:iam::*:role/ecsInfrastructureRole"],
            "Condition": {
                "StringEquals": {"iam:PassedToService": "ecs.amazonaws.com"}
            }
        }
    ]
}
```

------

For more information about `iam:Passrole` and updating permissions for your user, see [Granting a user permissions to pass a role to an AWS service](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_use_passrole.html) and [Changing permissions for an IAM user](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_users_change-permissions.html) in the *AWS Identity and Access Management User Guide*.

# Amazon ECS Managed Instances instance profile


An instance profile is an IAM container that holds exactly one IAM role and allows Amazon ECS Managed Instances to assume that role securely. The instance profile contains an instance role that the ECS agent assumes to register instances with clusters and communicate with the ECS service.

**Important**  
If you use Amazon ECS Managed Instances with the `AmazonECSInfrastructureRolePolicyForManagedInstances` managed policy, the instance role name must start with `ecsInstanceRole`. The policy scopes `iam:PassRole` to `arn:aws:iam::*:role/ecsInstanceRole*`, so a mismatched name causes an authorization error at task launch. This is common with CloudFormation when you omit `RoleName`, because CloudFormation auto-generates names like `MyStack-InstanceRole-ABC123`.  
If you use a custom infrastructure role policy instead, the instance role can have any name as long as your policy includes an `iam:PassRole` grant targeting the instance role ARN.

## Create the role with the trust policy


Replace all *user input* with your own information.

1. Create a file named `ecsInstanceRole-trust-policy.json` that contains the trust policy to use for the IAM role. The file should contain the following:

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

****  

   ```
   {
     "Version":"2012-10-17",		 	 	 
     "Statement": [
       {
         "Effect": "Allow",
         "Principal": { "Service": "ec2.amazonaws.com"},
         "Action": "sts:AssumeRole"
       }
     ]
   }
   ```

------

1. Use the following AWS CLI command to create a role named `ecsInstanceRole` by using the trust policy that you created in the previous step.

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

1. Attach the AWS managed `AmazonECSInstanceRolePolicyForManagedInstances` policy to the `ecsInstanceRole` role.

   ```
   aws iam attach-role-policy \
         --role-name ecsInstanceRole \
         --policy-arn arn:aws:iam::aws:policy/AmazonECSInstanceRolePolicyForManagedInstances
   ```
**Note**  
If you choose to apply least-privilege permissions and specify your own permissions instead, you can add the following permissions to help with troubleshooting task-related issues with Amazon ECS Managed Instances:   
`ecs:StartTelemetrySession`
`ecs:PutSystemLogEvents`

You can also use the IAM console's **Custom trust policy** workflow to create the role. For more information, see [Creating a role using custom trust policies (console)](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_create_for-custom.html) in the *IAM User Guide*.

After you create the file, you must grant your user permission to pass the role to Amazon ECS.

## Create the instance profile using the AWS CLI


After creating the role, create the instance profile using the AWS CLI:

```
aws iam create-instance-profile --instance-profile-name ecsInstanceRole 
```

Add the role to the instance profile:

```
aws iam add-role-to-instance-profile \
   --instance-profile-name ecsInstanceRole \
   --role-name ecsInstanceRole
```

Verify the profile was created successfully:

```
aws iam get-instance-profile --instance-profile-name ecsInstanceRole 
```

## Create the instance profile using CloudFormation


You can use AWS CloudFormation to create the instance role and instance profile. Choose one of the following options based on whether you use the AWS-managed infrastructure policy or a custom policy.

### Option 1: Use the ecsInstanceRole naming convention (recommended)


When you use the AWS-managed infrastructure policy, you must explicitly set `RoleName` to a value that starts with `ecsInstanceRole`. If you omit `RoleName`, CloudFormation auto-generates a name that does not match the managed policy's `iam:PassRole` condition, and tasks fail to launch.

```
Resources:
  EcsInstanceRole:
    Type: AWS::IAM::Role
    Properties:
      RoleName: ecsInstanceRole
      AssumeRolePolicyDocument:
        Version: "2012-10-17"
        Statement:
          - Effect: Allow
            Principal:
              Service: ec2.amazonaws.com
            Action: sts:AssumeRole
      ManagedPolicyArns:
        - arn:aws:iam::aws:policy/AmazonECSInstanceRolePolicyForManagedInstances

  EcsInstanceProfile:
    Type: AWS::IAM::InstanceProfile
    Properties:
      InstanceProfileName: ecsInstanceRole
      Roles:
        - !Ref EcsInstanceRole
```

### Option 2: Use a custom role name


If you prefer to let CloudFormation generate the role name, or you use a custom name that does not start with `ecsInstanceRole`, you must add an inline policy on your infrastructure role that grants `iam:PassRole` for the instance role.

```
Resources:
  EcsInstanceRole:
    Type: AWS::IAM::Role
    Properties:
      # No RoleName — CFN auto-generates
      AssumeRolePolicyDocument:
        Version: "2012-10-17"
        Statement:
          - Effect: Allow
            Principal:
              Service: ec2.amazonaws.com
            Action: sts:AssumeRole
      ManagedPolicyArns:
        - arn:aws:iam::aws:policy/AmazonECSInstanceRolePolicyForManagedInstances

  EcsInstanceProfile:
    Type: AWS::IAM::InstanceProfile
    Properties:
      Roles:
        - !Ref EcsInstanceRole

  EcsInfrastructureRole:
    Type: AWS::IAM::Role
    Properties:
      AssumeRolePolicyDocument:
        Version: "2012-10-17"
        Statement:
          - Effect: Allow
            Principal:
              Service: ecs.amazonaws.com
            Action: sts:AssumeRole
      ManagedPolicyArns:
        - arn:aws:iam::aws:policy/AmazonECSInfrastructureRolePolicyForManagedInstances
      Policies:
        - PolicyName: PassInstanceRoleToEC2
          PolicyDocument:
            Version: "2012-10-17"
            Statement:
              - Effect: Allow
                Action: iam:PassRole
                Resource: !GetAtt EcsInstanceRole.Arn
                Condition:
                  StringLike:
                    iam:PassedToService: "ec2.*"
```

## Troubleshooting


### Tasks fail with iam:PassRole authorization error


If your tasks fail with a `ResourceInitializationError` that mentions `iam:PassRole`, verify that your instance role name starts with `ecsInstanceRole`. You can check the auto-generated name in the CloudFormation console under your stack's **Resources** tab. If the name does not match, either:
+ Add `RoleName: ecsInstanceRole` to your `AWS::IAM::Role` resource.
+ Add an explicit `iam:PassRole` inline policy to your infrastructure role. For more information, see [Option 2: Use a custom role name](#create-instance-profile-cfn-custom).

# Amazon ECS infrastructure IAM role for load balancers
Infrastructure IAM role for load balancers

An Amazon ECS infrastructure IAM role for load balancers allows Amazon ECS to manage load balancer resources in your clusters on your behalf, and is used when:
+ You want to use blue/green deployments with Amazon ECS. The infrastructure role allows Amazon ECS to manage load balancer resources for your deployments.
+ You need Amazon ECS to create, modify, or delete load balancer resources such as target groups and listeners during deployment operations.

When Amazon ECS assumes this role to take actions on your behalf, the events will be visible in AWS CloudTrail. If Amazon ECS uses the role to manage load balancer resources for your blue/green deployments, the CloudTrail log `roleSessionName` will be `ECSNetworkingWithELB` or `ecs-service-scheduler`. You can use this name to search events in the CloudTrail console by filtering for **User name**.

Amazon ECS provides a managed policy which contains the permissions required for load balancer management. For more information see, [AmazonECSInfrastructureRolePolicyForLoadBalancers](https://docs.aws.amazon.com/aws-managed-policy/latest/reference/AmazonECSInfrastructureRolePolicyForLoadBalancers.html) in the *AWS Managed Policy Reference Guide*.

## Creating the Amazon ECS infrastructure role for load balancers


Replace all *user input* with your own information.

1. Create a file named `ecs-infrastructure-trust-policy.json` that contains the trust policy to use for the IAM role. The file should contain the following:

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

****  

   ```
   {
     "Version":"2012-10-17",		 	 	  
     "Statement": [ 
       {
         "Sid": "AllowAccessToECSForInfrastructureManagement", 
         "Effect": "Allow", 
         "Principal": {
           "Service": "ecs.amazonaws.com" 
         }, 
         "Action": "sts:AssumeRole" 
       } 
     ] 
   }
   ```

------

1. Use the following AWS CLI command to create a role named `ecsInfrastructureRoleForLoadBalancers` by using the trust policy that you created in the previous step.

   ```
   aws iam create-role \
         --role-name ecsInfrastructureRoleForLoadBalancers \
         --assume-role-policy-document file://ecs-infrastructure-trust-policy.json
   ```

1. Attach the AWS managed `AmazonECSInfrastructureRolePolicyForLoadBalancers` policy to the `ecsInfrastructureRoleForLoadBalancers` role.

   ```
   aws iam attach-role-policy \
         --role-name ecsInfrastructureRoleForLoadBalancers \
         --policy-arn arn:aws:iam::aws:policy/AmazonECSInfrastructureRolePolicyForLoadBalancers
   ```

You can also use the IAM console's **Custom trust policy** workflow to create the role. For more information, see [Creating a role using custom trust policies (console)](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_create_for-custom.html) in the *IAM User Guide*.

**Important**  
If the infrastructure role is being used by Amazon ECS to manage load balancer resources for your blue/green deployments, ensure the following before you delete or modify the role:  
The role isn't deleted while active deployments are in progress.
The trust policy for the role isn't modified to remove Amazon ECS access (`ecs.amazonaws.com`).
The managed policy `AmazonECSInfrastructureRolePolicyForLoadBalancers` isn't removed while active deployments are in progress.
Deleting or modifying the role during active blue/green deployments may result in deployment failures and could leave your services in an inconsistent state.

After you create the file, you must grant your user permission to pass the role to Amazon ECS.

## Permission to pass the infrastructure role to Amazon ECS


To use an ECS infrastructure IAM role for load balancers, you must grant your user permission to pass the role to Amazon ECS. Attach the following `iam:PassRole` permission to your user. Replace *ecsInfrastructureRoleForLoadBalancers* with the name of the infrastructure role that you created.

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

****  

```
{
    "Version":"2012-10-17",		 	 	 
    "Statement": [
        {
            "Action": "iam:PassRole",
            "Effect": "Allow",
            "Resource": ["arn:aws:iam::*:role/ecsInfrastructureRoleForLoadBalancers"],
            "Condition": {
                "StringEquals": {"iam:PassedToService": "ecs.amazonaws.com"}
            }
        }
    ]
}
```

------

For more information about `iam:Passrole` and updating permissions for your user, see [Granting a user permissions to pass a role to an AWS service](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_use_passrole.html) and [Changing permissions for an IAM user](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_users_change-permissions.html) in the *AWS Identity and Access Management User Guide*.

# Amazon ECS CodeDeploy IAM Role
CodeDeploy IAM Role

Before you can use the CodeDeploy blue/green deployment type with Amazon ECS, the CodeDeploy service needs permissions to update your Amazon ECS service on your behalf. These permissions are provided by the CodeDeploy IAM role (`ecsCodeDeployRole`).

**Note**  
Users also require permissions to use CodeDeploy; these permissions are described in [Required IAM permissions](deployment-type-bluegreen.md#deployment-type-bluegreen-IAM). 

There are two managed policies provided. For more information, see one of the following in the *AWS Managed Policy Reference Guide*:
+  [AWSCodeDeployRoleForECS](https://docs.aws.amazon.com/aws-managed-policy/latest/reference/AWSCodeDeployRoleForECS.html) - gives CodeDeploy permission to update any resource using the associated action. 
+ [AWSCodeDeployRoleForECSLimited](https://docs.aws.amazon.com/aws-managed-policy/latest/reference/AWSCodeDeployRoleForECSLimited.html) - gives CodeDeploy more limited permissions. 

## Creating the CodeDeploy role


You can use the following procedures to create a CodeDeploy role for Amazon ECS

------
#### [ AWS Management Console ]

**To create the service role for CodeDeploy (IAM console)**

1. Sign in to the AWS Management Console and open the IAM console at [https://console.aws.amazon.com/iam/](https://console.aws.amazon.com/iam/).

1. In the navigation pane of the IAM console, choose **Roles**, and then choose **Create role**.

1. For **Trusted entity type**, choose **AWS service**.

1. For **Service or use case**, choose **CodeDeploy**, and then choose the **CodeDeploy - ECS** use case.

1. Choose **Next**.

1. In the **Attach permissions policy** section, ensure that the **AWSCodeDeployRoleForECS** policy is selected.

1. Choose **Next**.

1.  For **Role name**, enter **ecsCodeDeployRole**.

1. Review the role, and then choose **Create role**.

------
#### [ AWS CLI ]

Replace all *user input* with your own information.

1. Create a file named `codedeploy-trust-policy.json` that contains the trust policy to use for the CodeDeploy IAM role.

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

****  

   ```
   {
       "Version":"2012-10-17",		 	 	 
       "Statement": [
           {
               "Sid": "",
               "Effect": "Allow",
               "Principal": {
                   "Service": ["codedeploy.amazonaws.com"]
               },
               "Action": "sts:AssumeRole"
           }
       ]
   }
   ```

------

1. Create an IAM role named `ecsCodedeployRole` using the trust policy created in the previous step.

   ```
   aws iam create-role \
         --role-name ecsCodedeployRole \
         --assume-role-policy-document file://codedeploy-trust-policy.json
   ```

1. Attach the `AWSCodeDeployRoleForECS` or `AWSCodeDeployRoleForECSLimited` managed policy to the `ecsTaskRole` role.

   ```
   aws iam attach-role-policy \
         --role-name ecsCodedeployRole \
         --policy-arn arn:aws:iam::aws:policy/AWSCodeDeployRoleForECS
   ```

   ```
   aws iam attach-role-policy \
         --role-name ecsCodedeployRole \
         --policy-arn arn:aws:iam::aws:policy/AWSCodeDeployRoleForECSLimited
   ```

------

When the tasks in your service need a task execution role, you must add the `iam:PassRole` permission for each task execution role or task role override to the CodeDeploy role as a policy. 

### Task execution role permissions


When the tasks in your service need a task execution role, you must add the `iam:PassRole` permission for each task execution role or task role override to the CodeDeploy role as a policy. For more information, see [Amazon ECS task execution IAM role](task_execution_IAM_role.md) and [Amazon ECS task IAM role](task-iam-roles.md). Then, you attach that policy to the CodeDeploy role

Create the policy

------
#### [ AWS Management Console ]

**To use the JSON policy editor to create a policy**

1. Sign in to the AWS Management Console and open the IAM console at [https://console.aws.amazon.com/iam/](https://console.aws.amazon.com/iam/).

1. In the navigation pane on the left, choose **Policies**. 

   If this is your first time choosing **Policies**, the **Welcome to Managed Policies** page appears. Choose **Get Started**.

1. At the top of the page, choose **Create policy**.

1. In the **Policy editor** section, choose the **JSON** option.

1. Enter the following JSON policy document:

   ```
   {
       "Version": "2012-10-17",		 	 	 
       "Statement": [
           {
               "Effect": "Allow",
               "Action": "iam:PassRole",
               "Resource": ["arn:aws:iam::<aws_account_id>:role/<ecsCodeDeployRole>"]
           }
       ]
   }
   ```

1. Choose **Next**.
**Note**  
You can switch between the **Visual** and **JSON** editor options anytime. However, if you make changes or choose **Next** in the **Visual** editor, IAM might restructure your policy to optimize it for the visual editor. For more information, see [Policy restructuring](https://docs.aws.amazon.com/IAM/latest/UserGuide/troubleshoot_policies.html#troubleshoot_viseditor-restructure) in the *IAM User Guide*.

1. On the **Review and create** page, enter a **Policy name** and a **Description** (optional) for the policy that you are creating. Review **Permissions defined in this policy** to see the permissions that are granted by your policy.

1. Choose **Create policy** to save your new policy.

After you create the policy, attach the policy to the CodeDeploy role. For information about how to attach the policy to the role, see [Update permissions for a role](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_update-role-permissions.html) in the *AWS Identity and Access Management User Guide*.

------
#### [ AWS CLI ]

Replace all *user input* with your own information.

1. Create a file called `blue-green-iam-passrole.json` with the following content.

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

****  

   ```
   {
       "Version":"2012-10-17",		 	 	 
       "Statement": [
           {
               "Effect": "Allow",
               "Action": "iam:PassRole",
               "Resource": ["arn:aws:iam::*:role/code-deploy-role"],
               "Condition": {
                       "StringEquals": {"iam:PassedToService": "ecs.amazonaws.com"}
               }
           }
       ]
   }
   ```

------

1. Use the following command to create the IAM policy using the JSON policy document file.

   ```
   aws iam create-policy \
         --policy-name cdTaskExecutionPolicy \
         --policy-document file://blue-green-iam-passrole.json
   ```

1. Retrieve the ARN of the IAM policy you created using the following command.

   ```
   aws iam list-policies --scope Local --query 'Policies[?PolicyName==`cdTaskExecutionPolicy`].Arn'
   ```

1. Use the following command to attach the policy to the CodeDeploy IAM role.

   ```
   aws iam attach-role-policy \
         --role-name ecsCodedeployRole \
         --policy-arn arn:aws:iam:111122223333:aws:policy/cdTaskExecutionPolicy
   ```

------

# Amazon ECS EventBridge IAM Role
EventBridge IAM Role

Before you can use Amazon ECS scheduled tasks with EventBridge rules and targets, the EventBridge service needs permissions to run Amazon ECS tasks on your behalf. These permissions are provided by the EventBridge IAM role (`ecsEventsRole`).

The `AmazonEC2ContainerServiceEventsRole` policy is shown below.

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

****  

```
{
    "Version":"2012-10-17",		 	 	 
    "Statement": [
        {
            "Effect": "Allow",
            "Action": ["ecs:RunTask"],
            "Resource": ["*"]
        },
        {
            "Effect": "Allow",
            "Action": "iam:PassRole",
            "Resource": ["*"],
            "Condition": {
                "StringLike": {"iam:PassedToService": "ecs-tasks.amazonaws.com"}
            }
        },
        {
            "Effect": "Allow",
            "Action": "ecs:TagResource",
            "Resource": "*",
            "Condition": {
                "StringEquals": {
                    "ecs:CreateAction": ["RunTask"]
                }
            }
        }
    ]
}
```

------

If your scheduled tasks require the use of the task execution role, a task role, or a task role override, then you must add `iam:PassRole` permissions for each task execution role, task role, or task role override to the EventBridge IAM role. For more information about the task execution role, see [Amazon ECS task execution IAM role](task_execution_IAM_role.md).

**Note**  
Specify the full ARN of your task execution role or task role override.

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

****  

```
{
    "Version":"2012-10-17",		 	 	 
    "Statement": [
        {
            "Effect": "Allow",
            "Action": "iam:PassRole",
            "Resource": [
            "arn:aws:iam::111122223333:role/ecsTaskExecutionRole_or_TaskRole_name"
            ]
        }
    ]
}
```

------

You can choose to let the AWS Management Console create the EventBridge role for you when you configure a scheduled task. For more information, see [Using Amazon EventBridge Scheduler to schedule Amazon ECS tasks](tasks-scheduled-eventbridge-scheduler.md).

## Creating the EventBridge role


Replace all *user input* with your own information.

1. Create a file named `eventbridge-trust-policy.json` that contains the trust policy to use for the IAM role. The file should contain the following:

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

****  

   ```
   {
     "Version":"2012-10-17",		 	 	 
     "Statement": [
       {
         "Sid": "",
         "Effect": "Allow",
         "Principal": {
           "Service": "events.amazonaws.com"
         },
         "Action": "sts:AssumeRole"
       }
     ]
   }
   ```

------

1. Use the following command to create an IAM role named `ecsEventsRole` by using the trust policy that you created in the previous step.

   ```
   aws iam create-role \
         --role-name ecsEventsRole \
         --assume-role-policy-document file://eventbridge-trust-policy.json
   ```

1. Attach the AWS managed `AmazonEC2ContainerServiceEventsRole` to the `ecsEventsRole` role using the following command.

   ```
   aws iam attach-role-policy \
         --role-name ecsEventsRole \
         --policy-arn arn:aws:iam::aws:policy/service-role/AmazonEC2ContainerServiceEventsRole
   ```

You can also use the IAM console's **Custom trust policy** workflow ([https://console.aws.amazon.com/iam/](https://console.aws.amazon.com/iam/)) to create the role. For more information, see [Creating a role using custom trust policies (console)](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_create_for-custom.html) in the *IAM User Guide*.

## Attaching a policy to the `ecsEventsRole` role


You can use the following procedures to add permissions for the task execution role to the EventBridge IAM role.

------
#### [ AWS Management Console ]

**To use the JSON policy editor to create a policy**

1. Sign in to the AWS Management Console and open the IAM console at [https://console.aws.amazon.com/iam/](https://console.aws.amazon.com/iam/).

1. In the navigation pane on the left, choose **Policies**. 

   If this is your first time choosing **Policies**, the **Welcome to Managed Policies** page appears. Choose **Get Started**.

1. At the top of the page, choose **Create policy**.

1. In the **Policy editor** section, choose the **JSON** option.

1. Enter the following JSON policy document:

   ```
   {
       "Version": "2012-10-17",		 	 	 
       "Statement": [
           {
               "Effect": "Allow",
               "Action": "iam:PassRole",
               "Resource": ["arn:aws:iam::111122223333:role/<ecsTaskExecutionRole_or_TaskRole_name>"]
           }
       ]
   }
   ```

1. Choose **Next**.
**Note**  
You can switch between the **Visual** and **JSON** editor options anytime. However, if you make changes or choose **Next** in the **Visual** editor, IAM might restructure your policy to optimize it for the visual editor. For more information, see [Policy restructuring](https://docs.aws.amazon.com/IAM/latest/UserGuide/troubleshoot_policies.html#troubleshoot_viseditor-restructure) in the *IAM User Guide*.

1. On the **Review and create** page, enter a **Policy name** and a **Description** (optional) for the policy that you are creating. Review **Permissions defined in this policy** to see the permissions that are granted by your policy.

1. Choose **Create policy** to save your new policy.

After you create the policy, attach the policy to the EventBridge role. For information about how to attach the policy to the role, see [Update permissions for a role](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_update-role-permissions.html) in the *AWS Identity and Access Management User Guide*.

------
#### [ AWS CLI ]

Replace all *user input* with your own information.

1. Create a file called `ev-iam-passrole.json` with the following content.

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

****  

   ```
   {
       "Version":"2012-10-17",		 	 	 
       "Statement": [
           {
               "Effect": "Allow",
               "Action": "iam:PassRole",
               "Resource": [
               "arn:aws:iam::111122223333:role/ecsTaskExecutionRole_or_TaskRole_name"
               ]
           }
       ]
   }
   ```

------

1. Use the following AWS CLI command to create the IAM policy using the JSON policy document file.

   ```
   aws iam create-policy \
         --policy-name eventsTaskExecutionPolicy \
         --policy-document file://ev-iam-passrole.json
   ```

1. Retrieve the ARN of the IAM policy you created using the following command.

   ```
   aws iam list-policies --scope Local --query 'Policies[?PolicyName==`eventsTaskExecutionPolicy`].Arn'
   ```

1. Use the following command to attach the policy to the EventBridge IAM role by using the policy ARN.

   ```
   aws iam attach-role-policy \
         --role-name ecsEventsRole \
         --policy-arn arn:aws:iam:111122223333:aws:policy/eventsTaskExecutionPolicy
   ```

------

# Permissions required for the Amazon ECS console


Following the best practice of granting least privilege, you can use the `AmazonECS_FullAccess` managed policy as a template for creating you own custom policy. That way, you can take away or add permissions to and from the managed policy based on your specific requirements. For more information, see [AmazonECS\$1FullAccess](https://docs.aws.amazon.com/aws-managed-policy/latest/reference/AmazonECS_FullAccess.html) in the *AWS Managed Policy Reference*.

## Permissions for creating IAM roles


The following actions require additional permissions in order to complete the operation:
+ Registering an external instance - for more information, see [Amazon ECS Anywhere IAM role](iam-role-ecsanywhere.md) 
+ Registering a task definition - for more information, see [Amazon ECS task execution IAM role](task_execution_IAM_role.md)
+ Creating an EventBridge rule to use for scheduling tasks - for more information, see [Amazon ECS EventBridge IAM Role](CWE_IAM_role.md)

You can add these permissions by creating a role in IAM before you use them in the Amazon ECS console. If you do not create the roles, the Amazon ECS console creates then on your behalf.

## Permissions required for registering an external instance to a cluster


You need additional permissions when you register an external instance to a cluster and you want to create a new external instance (`ecsExternalInstanceRole`) role. 

The following additional permissions are required:
+ `iam`– Allows principals to create and list IAM roles and their attached policies. 
  + iam:AttachRolePolicy
  + iam:CreateRole
  + am:CreateInstanceProfile
  + iam:AddRoleToInstanceProfile
  + iam:ListInstanceProfilesForRole
  + iam:GetRole
+ `ssm` – Allows principals to register the external instance with Systems Manager. 

**Note**  
In order to choose an existing `ecsExternalInstanceRole`, you must have the `iam:GetRole` and `iam:PassRole` permissions.

The following policy contains the required permissions, and limits the actions to the `ecsExternalInstanceRole` role. 

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

****  

```
{
"Statement": [
      {
          "Effect": "Allow",
          "Action": [
              "iam:AttachRolePolicy",
              "iam:CreateRole",
              "iam:CreateInstanceProfile",
              "iam:AddRoleToInstanceProfile",
              "iam:ListInstanceProfilesForRole",
              "iam:GetRole"
          ],
          "Resource": "arn:aws:iam::*:role/ecsExternalInstanceRole"
      },
      {
          "Effect": "Allow",
          "Action": ["iam:PassRole","ssm:CreateActivation"],
          "Resource": "arn:aws:iam::*:role/ecsExternalInstanceRole"
      }
    ]
}
```

------

## Permissions required for registering a task definition


You need additional permissions when you register a task definition and you want to create a new task execution (`ecsTaskExecutionRole`) role. 

The following additional permissions are required:
+ `iam`– Allows principals to create and list IAM roles and their attached policies. 
  + iam:AttachRolePolicy
  + iam:CreateRole
  + iam:GetRole

**Note**  
In order to choose an existing `ecsTaskExecutionRole`, you must have the `iam:GetRole` permission.

The following policy contains the required permissions, and limits the actions to the `ecsTaskExecutionRole` role. 

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

****  

```
{
"Statement": [
    {
        "Effect": "Allow",
        "Action": [
            "iam:AttachRolePolicy",
            "iam:CreateRole",
            "iam:GetRole"
        ],
        "Resource": "arn:aws:iam::*:role/ecsTaskExecutionRole"
        }
    ]
}
```

------

## Permissions required for using Amazon Q Developer to provide recommendations in the console


 For Amazon Q Developer to provide recommendations in the Amazon ECS; console, you must enable the correct IAM permissions for either your IAM user or role. You must add the `codewhisperer:GenerateRecommendations` permission.

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

****  

```
{
"Statement": [
      {
            "Sid": "AmazonQDeveloperPermissions",
            "Effect": "Allow",
            "Action": ["codewhisperer:GenerateRecommendations"],
            "Resource": "*"
        }
    ]
}
```

------

 To use inline chat in the Amazon ECS; console, you must enable the correct IAM permissions for either your IAM user or role. You must add the `q:SendMessage` permission.: 

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

****  

```
{
"Statement": [
    {
        "Sid": "AmazonQDeveloperInlineChatPermissions",
        "Effect": "Allow",
        "Action": ["q:SendMessage"],
        "Resource": "*"
    }
  ]
}
```

------

## Permissions required for creating an EventBridge rule for scheduled tasks


You need additional permissions when you schedule a task and you want to create a new CloudWatch Events role (`ecsEventsRole`) role. 

The following additional permissions are required:
+ `iam`– Allows principals to create and list IAM roles and their attached policies, and to allow Amazon ECS to pass the role to other services to assume the role.

**Note**  
In order to choose an existing `ecsEventsRole`, you must have the `iam:GetRole` and `iam:PassRole` permissions.

The following policy contains the required permissions, and limits the actions to the `ecsEventsRole` role. 

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

****  

```
{
 "Statement": [
    {
        "Effect": "Allow",
        "Action": [
            "iam:AttachRolePolicy",
            "iam:CreateRole",
            "iam:GetRole",
            "iam:PassRole"
        ],
        "Resource": "arn:aws:iam::*:role/ecsEventsRole"
        }
    ]
}
```

------

## Permissions required for viewing service deployments


 When you follow the best practice of granting least privilege, you need to add additional permissions in order to view service deployments in the console.

You need access to the following actions:
+ ListServiceDeployments
+ DescribeServiceDeployments
+ DescribeServiceRevisions

You need access to the following resources:
+ Service
+ Service deployment
+ Service revision

The following example policy contains the required permissions, and limits the actions to a specified service. 

Replace the `account`, `cluster-name`, and `service-name` with your values.

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

****  

```
{
"Statement": [
    {
        "Effect": "Allow",
        "Action": [
            "ecs:ListServiceDeployments",
            "ecs:DescribeServiceDeployments",
            "ecs:DescribeServiceRevisions"
        ],
        "Resource": [
            "arn:aws:ecs:us-east-1:123456789012:service/cluster-name/service-name",
            "arn:aws:ecs:us-east-1:123456789012:service-deployment/cluster-name/service-name/*",
            "arn:aws:ecs:us-east-1:123456789012:service-revision/cluster-name/service-name/*"
            ]
        }
   ]
}
```

------

## Permissions required to view Amazon ECS lifecycle events in Container Insights


The following permissions are required to view the lifecycle events. Add the following permissions as an inline policy to the role. For more information, see [Adding and Removing IAM Policies](https://docs.aws.amazon.com/IAM/latest/UserGuide/access_policies_manage-attach-detach.html)
+ events:DescribeRule
+ events:ListTargetsByRule
+ logs:DescribeLogGroups

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

****  

```
{
  "Version":"2012-10-17",		 	 	 
  "Statement": [
    {
      "Effect": "Allow",
      "Action": [
        "events:DescribeRule",
        "events:ListTargetsByRule",
        "logs:DescribeLogGroups"
      ],
      "Resource": "*"
    }
  ]
}
```

------

## Permissions required for enabling Amazon ECS lifecycle events in Container Insights


The following permissions are required to configure the lifecycle events:
+ events:PutRule
+ events:PutTargets
+ logs:CreateLogGroup

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

****  

```
{
  "Version":"2012-10-17",		 	 	 
  "Statement": [
    {
      "Effect": "Allow",
      "Action": [
        "events:PutRule",
        "events:PutTargets",
        "logs:CreateLogGroup"
      ],
      "Resource": "*"
    }
  ]
}
```

------

# Permissions required for the Amazon ECS console with CloudFormation


Before using the AWS Management Console to create your resources, you'll need to make sure to have the correct IAM permissions. For information on how to set up permissions for the Amazon ECS console in general first, see [Permissions required for the Amazon ECS console](https://docs.aws.amazon.com/AmazonECS/latest/developerguide/console-permissions.html).

The Amazon ECS console is powered by AWS CloudFormation and requires additional IAM permissions in the following cases:
+ Creating a cluster
+ Creating a service
+ Creating a capacity provider

You can create a policy for the additional permissions, and then attach them to the IAM role you use to access the console. For more information, see [Creating IAM policies](https://docs.aws.amazon.com/IAM/latest/UserGuide/access_policies_create.html#access_policies_create-start) in the *IAM User Guide*.

## Permissions required for creating a cluster


When you create a cluster in the console, you need additional permissions that grant you permissions to manage CloudFormation stacks. 

 The following additional permissions are required:
+ `cloudformation` – Allows principals to create and manage CloudFormation stacks. This is required when creating Amazon ECS clusters using the AWS Management Console and the subsequent managing of those clusters.
+ `ssm` – Allows CloudFormation to reference latest Amazon ECS-optimized AMI. This is required when creating Amazon ECS clusters using the AWS Management Console.

The following policy contains the required CloudFormation permissions, and limits the actions to resources created in the Amazon ECS console.

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

****  

```
{
  "Statement": [
      {
          "Effect": "Allow",
          "Action": [
                "cloudformation:CreateStack",
                "cloudformation:DeleteStack",
                "cloudformation:DescribeStack*",
                "cloudformation:UpdateStack"
             ],
            "Resource": [
                "arn:*:cloudformation:*:*:stack/Infra-ECS-Cluster-*"
            ]
      },
      {
          "Effect": "Allow",
          "Action": "ssm:GetParameters",
          "Resource": [
            "arn:aws:ssm:*:*:parameter/aws/service/ecs/optimized-ami/amazon-linux-2*/*",
            "arn:aws:ssm:*:*:parameter/aws/service/ecs/optimized-ami/amazon-linux-2023*/*"
          ]
      }
   ]
}
```

------

If you have not created the Amazon ECS container instance role (`ecsInstanceRole`), and you are creating a cluster that uses Amazon EC2 instances, then the console will create the role on your behalf.

In addition, if you use Auto Scaling groups, then you need additional permissions so that the console can add tags to the auto scaling groups when using the cluster auto scaling feature.

The following additional permissions are required:
+ `autoscaling` – Allows the console to tag Amazon EC2 Auto Scaling group. This is required when managing Amazon EC2 auto scaling groups when using the cluster auto scaling feature. The tag is the ECS-managed tag that the console automatically adds to the group to indicate is was created in the console.
+ `iam`– Allows principals to list IAM roles and their attached policies. Principals can also list instance profiles available to your Amazon EC2 instances.

The following policy contains the required IAM permissions, and limits the actions to the `ecsInstanceRole` role.

The Auto Scaling permissions are not limited.

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

****  

```
{
  "Statement": [
      {
          "Effect": "Allow",
            "Action": [
              "iam:AttachRolePolicy",
              "iam:CreateRole",
              "iam:CreateInstanceProfile",
              "iam:AddRoleToInstanceProfile",
              "iam:ListInstanceProfilesForRole",
              "iam:GetRole"
            ],
            "Resource": "arn:aws:iam::*:role/ecsInstanceRole"
        },
        {
            "Effect": "Allow",
            "Action": "autoscaling:CreateOrUpdateTags",
            "Resource": "*"
        }
    ]
}
```

------

## Permissions required for creating a service


When you create a service in the console, you need additional permissions that grant you permissions to manage CloudFormation stacks. The following additional permissions are required:
+ `cloudformation` – Allows principals to create and manage CloudFormation stacks. This is required when creating Amazon ECS services using the AWS Management Console and the subsequent managing of those services.

The following policy contains the required permissions, and limits the actions to resources created in the Amazon ECS console.

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

****  

```
{
  "Statement": [
      {
          "Effect": "Allow",
          "Action": [
                "cloudformation:CreateStack",
                "cloudformation:DeleteStack",
                "cloudformation:DescribeStack*",
                "cloudformation:UpdateStack"
             ],
            "Resource": [
                "arn:*:cloudformation:*:*:stack/ECS-Console-V2-Service-*"
            ]
      }
   ]
}
```

------

# Permissions required for Lambda functions in Amazon ECS blue/green deployments


When you use Lambda functions as deployment lifecycle hooks in Amazon ECS blue/green deployments, you need to create an IAM role with specific permissions. This role allows Amazon ECS to invoke your Lambda functions at various stages of the deployment lifecycle.

The following additional permissions are required:
+ `lambda:InvokeFunction` – Allows Amazon ECS to invoke Lambda functions configured as lifecycle hooks during the deployment process.

For the trust policy, you need to allow the service to assume this role:

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

****  

```
{
    "Version":"2012-10-17",		 	 	 
    "Statement": [
        {
            "Effect": "Allow",
            "Principal": {
                "Service": [
                    "ecs.amazonaws.com"
                ]
            },
            "Action": "sts:AssumeRole"
        }
    ]
}
```

------

# IAM permissions required for Amazon ECS service auto scaling


Service Auto Scaling is made possible by a combination of the Amazon ECS, CloudWatch, and Application Auto Scaling APIs. Services are created and updated with Amazon ECS, alarms are created with CloudWatch, and scaling policies are created with Application Auto Scaling. 

In addition to the standard IAM permissions for creating and updating services, the following permissions are required to interact with Service Auto Scaling settings.
+ `application-autoscaling:*`
+ `ecs:DescribeServices`
+ `ecs:UpdateService`
+ `cloudwatch:DescribeAlarms`
+ `cloudwatch:PutMetricAlarm`
+ `cloudwatch:DeleteAlarms`
+ `cloudwatch:DescribeAlarmHistory`
+ `cloudwatch:DescribeAlarmsForMetric`
+ `cloudwatch:GetMetricStatistics`
+ `cloudwatch:ListMetrics`
+ `cloudwatch:DisableAlarmActions`
+ `cloudwatch:EnableAlarmActions`
+ `iam:CreateServiceLinkedRole`
+ `sns:CreateTopic`
+ `sns:Subscribe`
+ `sns:Get*`
+ `sns:List*`

The Application Auto Scaling service also needs permission to describe your Amazon ECS services and CloudWatch alarms, and permissions to modify your service's desired count on your behalf. The `sns:` permissions are for the notifications that CloudWatch sends to an Amazon SNS topic when a threshold has been exceeded. If you use automatic scaling for your Amazon ECS services, it creates a service-linked role named `AWSServiceRoleForApplicationAutoScaling_ECSService`. This service-linked role grants Application Auto Scaling permission to describe the alarms for your policies, to monitor the current running task count of the service, and to modify the desired count of the service. The original managed Amazon ECS role for Application Auto Scaling was `ecsAutoscaleRole`, but it is no longer required. The service-linked role is the default role for Application Auto Scaling. For more information, see [Service-linked roles for Application Auto Scaling](https://docs.aws.amazon.com/autoscaling/application/userguide/application-auto-scaling-service-linked-roles.html) in the *Application Auto Scaling User Guide*.

If you created your Amazon ECS container instance role before CloudWatch metrics are available for Amazon ECS, you might need to add the `ecs:StartTelemetrySession` permission. For more information, see [Considerations](cloudwatch-metrics.md#enable_cloudwatch).

# Grant permission to tag resources on creation
Tag resources during creation

The following tag-on create Amazon ECS API actions allow you to specify tags when you create the resource. If tags are specified in the resource-creating action, AWS performs additional authorization to verify that the correct permissions are assigned to create tags. 
+ `CreateCapacityProvider`
+ `CreateCluster`
+ `CreateService`
+ `CreateTaskSet`
+ `RegisterContainerInstance`
+ `RegisterTaskDefinition`
+ `RunTask`
+ `StartTask`

You can use resource tags to implement attribute-based control (ABAC). For more information, see [Control access to Amazon ECS resources using resource tags](control-access-with-tags.md) and [Tagging Amazon ECS resources](ecs-using-tags.md).

To allow tagging on creation, create or modify a policy to include both the permissions to use the action that creates the resource, such as `ecs:CreateCluster` or `ecs:RunTask` and the `ecs:TagResource` action. 

The following example demonstrates a policy that allows users to create clusters and add tags during the cluster creation. Users are not permitted to tag any existing resources (they cannot call the `ecs:TagResource` action directly).

```
{
  "Statement": [
    {
      "Effect": "Allow",
      "Action": [
         "ecs:CreateCluster"
      ],
      "Resource": "*"
    },
    {
      "Effect": "Allow",
      "Action": [
         "ecs:TagResource"
      ],
      "Resource": "*",
      "Condition": {
         "StringEquals": {
                  "ecs:CreateAction": [
                      "CreateCluster",
                      "CreateCapacityProvider",
                      "CreateService",
                      "CreateTaskSet",
                      "RegisterContainerInstance",
                      "RegisterTaskDefinition",
                      "RunTask",
                      "StartTask"
                  ]
          }
       }
    }
  ]
}
```

The `ecs:TagResource` action is only evaluated if tags are applied during the resource-creating action. Therefore, a user that has permissions to create a resource (assuming there are no tagging conditions) does not require permissions to use the `ecs:TagResource` action if no tags are specified in the request. However, if the user attempts to create a resource with tags, the request fails if the user does not have permissions to use the `ecs:TagResource` action.

## Amazon ECS control access to specific tags


You can use additional conditions in the `Condition` element of your IAM policies to control the tag keys and values that can be applied to resources.

The following condition keys can be used with the examples in the preceding section:
+ `aws:RequestTag`: To indicate that a particular tag key or tag key and value must be present in a request. Other tags can also be specified in the request.
  + Use with the `StringEquals` condition operator to enforce a specific tag key and value combination, for example, to enforce the tag `cost-center`=`cc123`:

    ```
    "StringEquals": { "aws:RequestTag/cost-center": "cc123" }
    ```
  + Use with the `StringLike` condition operator to enforce a specific tag key in the request; for example, to enforce the tag key `purpose`:

    ```
    "StringLike": { "aws:RequestTag/purpose": "*" }
    ```
+ `aws:TagKeys`: To enforce the tag keys that are used in the request.
  + Use with the `ForAllValues` modifier to enforce specific tag keys if they are provided in the request (if tags are specified in the request, only specific tag keys are allowed; no other tags are allowed). For example, the tag keys `environment` or `cost-center` are allowed:

    ```
    "ForAllValues:StringEquals": { "aws:TagKeys": ["environment","cost-center"] }
    ```
  + Use with the `ForAnyValue` modifier to enforce the presence of at least one of the specified tag keys in the request. For example, at least one of the tag keys `environment` or `webserver` must be present in the request:

    ```
    "ForAnyValue:StringEquals": { "aws:TagKeys": ["environment","webserver"] }
    ```

These condition keys can be applied to resource-creating actions that support tagging, as well as the `ecs:TagResource` action. To learn whether an Amazon ECS API action supports tagging, see [Actions, resources, and condition keys for Amazon ECS](https://docs.aws.amazon.com/service-authorization/latest/reference/list_amazonelasticcontainerservice.html).

To force users to specify tags when they create a resource, you must use the `aws:RequestTag` condition key or the `aws:TagKeys` condition key with the `ForAnyValue` modifier on the resource-creating action. The `ecs:TagResource` action is not evaluated if a user does not specify tags for the resource-creating action.

For conditions, the condition key is not case-sensitive and the condition value is case-sensitive. Therefore, to enforce the case-sensitivity of a tag key, use the `aws:TagKeys` condition key, where the tag key is specified as a value in the condition.

 For more information about multi-value conditions, see [Conditions with multiple context keys or values](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_condition-logic-multiple-context-keys-or-values.html) in the *IAM User Guide*. 

# Control access to Amazon ECS resources using resource tags


When you create an IAM policy that grants users permission to use Amazon ECS resources, you can include tag information in the `Condition` element of the policy to control access based on tags. This is known as attribute-based access control (ABAC). ABAC provides better control over which resources a user can modify, use, or delete. For more information, see [What is ABAC for AWS?](https://docs.aws.amazon.com/IAM/latest/UserGuide/introduction_attribute-based-access-control.html)

For example, you can create a policy that allows users to delete a cluster, but denies the action if the cluster has the tag `environment=production`. To do this, you use the `aws:ResourceTag` condition key to allow or deny access to the resource based on the tags that are attached to the resource.

```
"StringEquals": { "aws:ResourceTag/environment": "production" }
```

To learn whether an Amazon ECS API action supports controlling access using the `aws:ResourceTag` condition key, see [Actions, resources, and condition keys for Amazon ECS](https://docs.aws.amazon.com/service-authorization/latest/reference/list_amazonelasticcontainerservice.html). Note that the `Describe` actions do not support resource-level permissions, so you must specify them in a separate statement without conditions.

For example IAM policies, see [Amazon ECS Example policies](iam-policies-ecs-console.md). 

If you allow or deny users access to resources based on tags, you must consider explicitly denying users the ability to add those tags to or remove them from the same resources. Otherwise, it's possible for a user to circumvent your restrictions and gain access to a resource by modifying its tags.

# Amazon ECS Example policies
Example policies

You can use IAM policies to grant users permissions to view and work with specific resources in the Amazon ECS console. You can use the example policies in the previous section; however, they are designed for requests that are made with the AWS CLI or an AWS SDK.

## Example: Allow users to delete an Amazon ECS cluster based on tags


The following policy allows users to delete clusters when the tag has a key/value pair of "Purpose/Testing".

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

****  

```
{
    "Version":"2012-10-17",		 	 	 
    "Statement": [
        {
            "Action": [
                "ecs:DeleteCluster"
            ],
            "Effect": "Allow",
            "Resource": "arn:aws:ecs:us-east-1:111122223333:cluster/*",
            "Condition": {
                "StringEquals": {
                    "aws:ResourceTag/Purpose": "Testing"
                }
            }
        }
    ]
}
```

------

# Troubleshooting Amazon Elastic Container Service identity and access
Troubleshooting

Use the following information to help you diagnose and fix common issues that you might encounter when working with Amazon ECS and IAM.

**Topics**
+ [

## I am not authorized to perform an action in Amazon ECS
](#security_iam_troubleshoot-no-permissions)
+ [

## I am not authorized to perform iam:PassRole
](#security_iam_troubleshoot-passrole)
+ [

## I want to allow people outside of my AWS account to access my Amazon ECS resources
](#security_iam_troubleshoot-cross-account-access)
+ [

## I am having issues with my Amazon ECS Managed Instances instance profile
](#security_iam_instance-profile)
+ [

## Additional troubleshooting resources
](#security_iam_troubleshoot-additional-errors)

## I am not authorized to perform an action in Amazon ECS


If you receive an error that you're not authorized to perform an action, your policies must be updated to allow you to perform the action.

The following example error occurs when the `mateojackson` IAM user tries to use the console to view details about a fictional `my-example-widget` resource but doesn't have the fictional `ecs:GetWidget` permissions.

```
User: arn:aws:iam::123456789012:user/mateojackson is not authorized to perform: ecs:GetWidget on resource: my-example-widget
```

In this case, the policy for the `mateojackson` user must be updated to allow access to the `my-example-widget` resource by using the `ecs:GetWidget` action.

If you need help, contact your AWS administrator. Your administrator is the person who provided you with your sign-in credentials.

## I am not authorized to perform iam:PassRole


If you receive an error that you're not authorized to perform the `iam:PassRole` action, your policies must be updated to allow you to pass a role to Amazon ECS.

Some AWS services allow you to pass an existing role to that service instead of creating a new service role or service-linked role. To do this, you must have permissions to pass the role to the service.

The following example error occurs when an IAM user named `marymajor` tries to use the console to perform an action in Amazon ECS. However, the action requires the service to have permissions that are granted by a service role. Mary does not have permissions to pass the role to the service.

```
User: arn:aws:iam::123456789012:user/marymajor is not authorized to perform: iam:PassRole
```

In this case, Mary's policies must be updated to allow her to perform the `iam:PassRole` action.

If you need help, contact your AWS administrator. Your administrator is the person who provided you with your sign-in credentials.

## I want to allow people outside of my AWS account to access my Amazon ECS resources


You can create a role that users in other accounts or people outside of your organization can use to access your resources. You can specify who is trusted to assume the role. For services that support resource-based policies or access control lists (ACLs), you can use those policies to grant people access to your resources.

To learn more, consult the following:
+ To learn whether Amazon ECS supports these features, see [How Amazon Elastic Container Service works with IAM](security_iam_service-with-iam.md).
+ To learn how to provide access to your resources across AWS accounts that you own, see [Providing access to an IAM user in another AWS account that you own](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_common-scenarios_aws-accounts.html) in the *IAM User Guide*.
+ To learn how to provide access to your resources to third-party AWS accounts, see [Providing access to AWS accounts owned by third parties](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_common-scenarios_third-party.html) in the *IAM User Guide*.
+ To learn how to provide access through identity federation, see [Providing access to externally authenticated users (identity federation)](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_common-scenarios_federated-users.html) in the *IAM User Guide*.
+ To learn the difference between using roles and resource-based policies for cross-account access, see [Cross account resource access in IAM](https://docs.aws.amazon.com/IAM/latest/UserGuide/access_policies-cross-account-resource-access.html) in the *IAM User Guide*.

## I am having issues with my Amazon ECS Managed Instances instance profile


If you use the `AmazonECSInfrastructureRolePolicyForManagedInstances` managed policy that Amazon ECS provides, then the instance profile must have `ecsInstanceRole` as prefix. The reason is that the managed policy is only authorized to pass roles with this prefix.

## Additional troubleshooting resources


The following pages provide information about error codes:
+  [Amazon ECS stopped tasks error messages](stopped-task-error-codes.md) 
+  [Viewing Amazon ECS service event messages](service-event-messages.md) 

# IAM best practices for Amazon ECS
IAM best practices

You can use AWS Identity and Access Management (IAM) to manage and control access to your AWS services and resources through rule-based policies for authentication and authorization purposes. More specifically, through this service, you control access to your AWS resources by using policies that are applied to users, groups, or roles. Among these three, users are accounts that can have access to your resources. And, an IAM role is a set of permissions that can be assumed by an authenticated identity, which isn't associated with a particular identity outside of IAM. For more information, see [Amazon ECS overview of access management: Permissions and policies](https://docs.aws.amazon.com/IAM/latest/UserGuide/introduction_access-management.html).

## Follow the policy of least privileged access


Create policies that are scoped to allow users to perform their prescribed jobs. For example, if a developer needs to periodically stop a task, create a policy that only permits that particular action. The following example only allows a user to stop a task that belongs to a particular `task_family` on a cluster with a specific Amazon Resource Name (ARN). Referring to an ARN in a condition is also an example of using resource-level permissions. You can use resource-level permissions to specify the resource that you want an action to apply to. For more information, see [Policy resources for Amazon ECS](https://docs.aws.amazon.com/AmazonECS/latest/developerguide/security_iam_service-with-iam.html#security_iam_service-with-iam-id-based-policies-resources).

## Have cluster resources serve as the administrative boundary


Policies that are too narrowly scoped can cause a proliferation of roles and increase administrative overhead. Rather than creating roles that are scoped to particular tasks or services only, create roles that are scoped to clusters and use the cluster as your primary administrative boundary.

## Create automated pipelines to isolate end-users from the API


You can limit the actions that users can use by creating pipelines that automatically package and deploy applications onto Amazon ECS clusters. This effectively delegates the job of creating, updating, and deleting tasks to the pipeline. For more information, see [Tutorial: Amazon ECS standard deployment with CodePipeline](https://docs.aws.amazon.com/codepipeline/latest/userguide/ecs-cd-pipeline.html) in the *AWS CodePipeline User Guide*.

## Use policy conditions for an added layer of security


When you need an added layer of security, add a condition to your policy. This can be useful if you're performing a privileged operation or when you need to restrict the set of actions that can be performed against particular resources. The following example policy requires multi-factor authorization when deleting a cluster.

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

****  

```
{
  "Version":"2012-10-17",		 	 	 
  "Statement": [
    {
      "Effect": "Allow",
      "Action": [
        "ecs:DeleteCluster"
      ],
      "Condition": {
        "Bool": {
          "aws:MultiFactorAuthPresent": "true"
        }
      },
    "Resource": ["*"]
    }
  ]
}
```

------

Tags applied to services are propagated to all the tasks that are part of that service. Because of this, you can create roles that are scoped to Amazon ECS resources with specific tags. In the following policy, an IAM principal starts and stops all tasks with a tag-key of `Department` and a tag-value of `Accounting`.

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

****  

```
{
    "Version":"2012-10-17",		 	 	 
    "Statement": [
        {
            "Effect": "Allow",
            "Action": [
                "ecs:StartTask",
                "ecs:StopTask",
                "ecs:RunTask"
            ],
            "Resource": "arn:aws:ecs:us-east-1:123456789012:cluster/my-cluster",
            "Condition": {
                "StringEquals": {"ecs:ResourceTag/Department": "Accounting"}
            }
        }
    ]
}
```

------

## Periodically audit access to the APIs


A user might change roles. After they change roles, the permissions that were previously granted to them might no longer apply. Make sure that you audit who has access to the Amazon ECS APIs and whether that access is still warranted. Consider integrating IAM with a user lifecycle management solution that automatically revokes access when a user leaves the organization. For more information, see [AWS security audit guidelines](https://docs.aws.amazon.com/IAM/latest/UserGuide/security-audit-guide.html) in the *AWS Identity and Access Management User Guide*.