

# Define which container instances Amazon ECS uses for tasks
Define which container instances are used for tasks

A task placement constraint is a rule about a container instance that Amazon ECS uses to determine if the task is allowed to run on the instance. At least one container instance must match the constraint. If there are no instances that match the constraint, the task remains in a `PENDING` state. When you create a new service or update an existing one, you can specify task placement constraints for the service's tasks. 

You can specify task placement constraints in the service definition, task definition, or task using the `placementConstraint` parameter.

```
"placementConstraints": [
    {
        "expression": "The expression that defines the task placement constraints",
        "type": "The placement constraint type to use"
    }
]
```

The following table describes how to use the parameters.


| Constraint type | Can be specified when | 
| --- | --- | 
| distinctInstancePlace each active task on a different container instance.Amazon ECS looks at the desired status of the tasks for the task placement. For example, if the desired status of the existing task is `STOPPED`, (but the last status isn’t), a new incoming task can be placed on the same instance despite the `distinctInstance` placement constraint. Therefore, you might see 2 tasks with last status of `RUNNING` on the same instance. We recommend that customers looking for strong isolation for their tasks use Fargate. Fargate runs each task in a hardware virtualization environment. This ensures that these containerized workloads do not share network interfaces, Fargate ephemeral storage, CPU, or memory with other tasks. For more information, see [Security Overview of AWS Fargate](https://d1.awsstatic.com/whitepapers/AWS_Fargate_Security_Overview_Whitepaper.pdf). |  [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/AmazonECS/latest/developerguide/task-placement-constraints.html)  | 
| memberOfPlace tasks on container instances that satisfy an expression.  | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/AmazonECS/latest/developerguide/task-placement-constraints.html) | 

When you use the `memberOf` constraint type, you can create an expression using the cluster query language which defines the container instances where Amazon ECS can place tasks. The expression is a way for you to group your container instances by attributes. The expression goes in the `expression `parameter of `placementConstraint`.

## Amazon ECS container instance attributes


You can add custom metadata to your container instances, known as *attributes*. Each attribute has a name and an optional string value. You can use the built-in attributes provided by Amazon ECS or define custom attributes.

The following sections contain sample built-in, optional, and custom attributes.

### Built-in attributes


Amazon ECS automatically applies the following attributes to your container instances.

`ecs.ami-id`  
The ID of the AMI used to launch the instance. An example value for this attribute is `ami-1234abcd`.

`ecs.availability-zone`  
The Availability Zone for the instance. An example value for this attribute is `us-east-1a`.

`ecs.instance-type`  
The instance type for the instance. An example value for this attribute is `g2.2xlarge`.

`ecs.os-type`  
The operating system for the instance. The possible values for this attribute are `linux` and `windows`.

`ecs.os-family`  
The operating system version for the instance.  
For Linux instances, the valid value is `LINUX`. For Windows instances, ECS sets the value in the `WINDOWS_SERVER_<OS_Release>_<FULL or CORE>` format. The valid values are `WINDOWS_SERVER_2022_FULL`, `WINDOWS_SERVER_2022_CORE`, `WINDOWS_SERVER_20H2_CORE`, `WINDOWS_SERVER_2019_FULL`, `WINDOWS_SERVER_2019_CORE`, and `WINDOWS_SERVER_2016_FULL`.  
This is important for Windows containers and Windows containers on AWS Fargate because the OS version of every Windows container must match that of the host. If the Windows version of the container image is different than the host, the container doesn't start. For more information, see [Windows container version compatibility](https://learn.microsoft.com/en-us/virtualization/windowscontainers/deploy-containers/version-compatibility?tabs=windows-server-2022%2Cwindows-11) on the Microsoft documentation website.  
If your cluster runs multiple Windows versions, you can ensure that a task is placed on an EC2 instance running on the same version by using the placement constraint: `memberOf(attribute:ecs.os-family == WINDOWS_SERVER_<OS_Release>_<FULL or CORE>)`. For more information, see [Retrieving Amazon ECS-optimized Windows AMI metadata](retrieve-ecs-optimized_windows_AMI.md).

`ecs.cpu-architecture`  
The CPU architecture for the instance. Example values for this attribute are `x86_64` and `arm64`.

`ecs.vpc-id`  
The VPC the instance was launched into. An example value for this attribute is `vpc-1234abcd`.

`ecs.subnet-id`  
The subnet the instance is using. An example value for this attribute is `subnet-1234abcd`.

**Note**  
Amazon ECS Managed Instances supports the following subset of attributes:  
`ecs.subnet-id`
`ecs.availability-zone`
`ecs.instance-type`
`ecs.cpu-architecture`

### Optional attributes


Amazon ECS may add the following attributes to your container instances.

`ecs.awsvpc-trunk-id`  
If this attribute exists, the instance has a trunk network interface. For more information, see [Increasing Amazon ECS Linux container instance network interfaces](container-instance-eni.md).

`ecs.outpost-arn`  
If this attribute exists, it contains the Amazon Resource Name (ARN) of the Outpost. For more information, see [Amazon Elastic Container Service on AWS Outposts](using-outposts.md).

`ecs.capability.external`  
If this attribute exists, the instance is identified as an external instance. For more information, see [Amazon ECS clusters for external instances](ecs-anywhere.md).

### Custom attributes


You can apply custom attributes to your container instances. For example, you can define an attribute with the name "stack" and a value of "prod".

When specifying custom attributes, you must consider the following.
+ The `name` must contain between 1 and 128 characters and name may contain letters (uppercase and lowercase), numbers, hyphens, underscores, forward slashes, back slashes, or periods.
+ The `value` must contain between 1 and 128 characters and may contain letters (uppercase and lowercase), numbers, hyphens, underscores, periods, at signs (@), forward slashes, back slashes, colons, or spaces. The value can't contain any leading or trailing whitespace.

# Create expressions to define container instances for Amazon ECS tasks
Create expressions to define container instances for tasks

Cluster queries are expressions that allow you to group objects. For example, you can group container instances by attributes such as Availability Zone, instance type, or custom metadata. For more information, see [Amazon ECS container instance attributes](task-placement-constraints.md#attributes).

After you have defined a group of container instances, you can customize Amazon ECS to place tasks on container instances based on group. For more information, see [Running an application as an Amazon ECS task](standalone-task-create.md), and [Creating an Amazon ECS rolling update deployment](create-service-console-v2.md). You can also apply a group filter when listing container instances.

## Expression syntax


Expressions have the following syntax:

```
subject operator [argument]
```

**Subject**  
The attribute or field to be evaluated.

`agentConnected`  
Select container instances by their Amazon ECS container agent connection status. You can use this filter to search for instances with container agents that are disconnected.  
Valid operators: equals (==), not\$1equals (\$1=), in, not\$1in (\$1in), matches (=\$1), not\$1matches (\$1\$1)

`agentVersion`  
Select container instances by their Amazon ECS container agent version. You can use this filter to find instances that are running outdated versions of the Amazon ECS container agent.  
Valid operators: equals (==), not\$1equals (\$1=), greater\$1than (>), greater\$1than\$1equal (>=), less\$1than (<), less\$1than\$1equal (<=)

`attribute:attribute-name`  
Select container instances by attribute. For more information, see [Amazon ECS container instance attributes](task-placement-constraints.md#attributes).

`ec2InstanceId`  
Select container instances by their Amazon EC2 instance ID.  
Valid operators: equals (==), not\$1equals (\$1=), in, not\$1in (\$1in), matches (=\$1), not\$1matches (\$1\$1)

`registeredAt`  
Select container instances by their container instance registration date. You can use this filter to find newly registered instances or instances that are very old.  
Valid operators: equals (==), not\$1equals (\$1=), greater\$1than (>), greater\$1than\$1equal (>=), less\$1than (<), less\$1than\$1equal (<=)  
Valid date formats: 2018-06-18T22:28:28\$100:00, 2018-06-18T22:28:28Z, 2018-06-18T22:28:28, 2018-06-18

`runningTasksCount`  
Select container instances by number of running tasks. You can use this filter to find instances that are empty or near empty (few tasks running on them).  
Valid operators: equals (==), not\$1equals (\$1=), greater\$1than (>), greater\$1than\$1equal (>=), less\$1than (<), less\$1than\$1equal (<=)

`task:group`  
Select container instances by task group. For more information, see [Group related Amazon ECS tasks](task-groups.md).

**Operator**  
The comparison operator. The following operators are supported.


|  Operator  |  Description  | 
| --- | --- | 
|  ==, equals  |  String equality  | 
|  \$1=, not\$1equals  |  String inequality  | 
|  >, greater\$1than  |  Greater than  | 
|  >=, greater\$1than\$1equal  |  Greater than or equal to  | 
|  <, less\$1than  |  Less than  | 
|  <=, less\$1than\$1equal  |  Less than or equal to  | 
|  exists  |  Subject exists  | 
|  \$1exists, not\$1exists  |  Subject doesn't exist  | 
|  in  |  Value in argument list  | 
|  \$1in, not\$1in  |  Value not in argument list  | 
|  =\$1, matches  |  Pattern match  | 
|  \$1\$1, not\$1matches  |  Pattern mismatch  | 

**Note**  
A single expression can't contain parentheses. However, parentheses can be used to specify precedence in compound expressions.

**Argument**  
For many operators, the argument is a literal value.

The `in` and `not_in` operators expect an argument list as the argument. You specify an argument list as follows:

```
[argument1, argument2, ..., argumentN]
```

The matches and not\$1matches operators expect an argument that conforms to the Java regular expression syntax. For more information, see [java.util.regex.Pattern](http://docs.oracle.com/javase/6/docs/api/java/util/regex/Pattern.html).

**Compound expressions**

You can combine expressions using the following Boolean operators:
+ &&, and
+ \$1\$1, or
+ \$1, not

You can specify precedence using parentheses:

```
(expression1 or expression2) and expression3
```

## Example expressions


The following are example expressions.

**Example: String Equality**  
The following expression selects instances with the specified instance type.

```
attribute:ecs.instance-type == t2.small
```

**Example: Argument List**  
The following expression selects instances in the us-east-1a or us-east-1b Availability Zone.

```
attribute:ecs.availability-zone in [us-east-1a, us-east-1b]
```

**Example: Compound Expression**  
The following expression selects G2 instances that aren't in the us-east-1d Availability Zone.

```
attribute:ecs.instance-type =~ g2.* and attribute:ecs.availability-zone != us-east-1d
```

**Example: Task Affinity**  
The following expression selects instances that are hosting tasks in the `service:production` group.

```
task:group == service:production
```

**Example: Task Anti-Affinity**  
The following expression selects instances that aren't hosting tasks in the database group.

```
not(task:group == database)
```

**Example: Running task count**  
The following expression selects instances that are only running one task.

```
runningTasksCount == 1
```

**Example: Amazon ECS container agent version**  
The following expression selects instances that are running a container agent version below 1.14.5.

```
agentVersion < 1.14.5
```

**Example: Instance registration time**  
The following expression selects instances that were registered before February 13, 2018.

```
registeredAt < 2018-02-13
```

**Example: Amazon EC2 instance ID**  
The following expression selects instances with the following Amazon EC2 instance IDs.

```
ec2InstanceId in ['i-abcd1234', 'i-wxyx7890']
```

# Example Amazon ECS task placement constraints
Example task placement constraints

The following are task placement constraint examples.

This example uses the `memberOf` constraint to place tasks on t2 instances. It can be specified with the following actions: [CreateService](https://docs.aws.amazon.com/AmazonECS/latest/APIReference/API_CreateService.html), [UpdateService](https://docs.aws.amazon.com/AmazonECS/latest/APIReference/API_UpdateService.html), [RegisterTaskDefinition](https://docs.aws.amazon.com/AmazonECS/latest/APIReference/API_RegisterTaskDefinition.html), and [RunTask](https://docs.aws.amazon.com/AmazonECS/latest/APIReference/API_RunTask.html).

```
"placementConstraints": [
    {
        "expression": "attribute:ecs.instance-type =~ t2.*",
        "type": "memberOf"
    }
]
```

The example uses the `memberOf` constraint to place replica tasks on instances with tasks in the daemon service `daemon-service` task group, respecting any task placement strategies that are also specified. This constraint ensures that the daemon service tasks get placed on the EC2 instance prior to the replica service tasks.

Replace `daemon-service` with the name of the daemon service.

```
"placementConstraints": [
    {
        "expression": "task:group == service:daemon-service",
        "type": "memberOf"
    }
]
```

The example uses the `memberOf` constraint to place tasks on instances with other tasks in the `databases` task group, respecting any task placement strategies that are also specified. For more information about task groups, see [Group related Amazon ECS tasks](task-groups.md). It can be specified with the following actions: [CreateService](https://docs.aws.amazon.com/AmazonECS/latest/APIReference/API_CreateService.html), [UpdateService](https://docs.aws.amazon.com/AmazonECS/latest/APIReference/API_UpdateService.html), [RegisterTaskDefinition](https://docs.aws.amazon.com/AmazonECS/latest/APIReference/API_RegisterTaskDefinition.html), and [RunTask](https://docs.aws.amazon.com/AmazonECS/latest/APIReference/API_RunTask.html).

```
"placementConstraints": [
    {
        "expression": "task:group == databases",
        "type": "memberOf"
    }
]
```

The `distinctInstance` constraint places each task in the group on a different instance. It can be specified with the following actions: [CreateService](https://docs.aws.amazon.com/AmazonECS/latest/APIReference/API_CreateService.html), [UpdateService](https://docs.aws.amazon.com/AmazonECS/latest/APIReference/API_UpdateService.html), and [RunTask](https://docs.aws.amazon.com/AmazonECS/latest/APIReference/API_RunTask.html)

Amazon ECS looks at the desired status of the tasks for the task placement. For example, if the desired status of the existing task is `STOPPED`, (but the last status isn’t), a new incoming task can be placed on the same instance despite the `distinctInstance` placement constraint. Therefore, you might see 2 tasks with last status of `RUNNING` on the same instance.

```
"placementConstraints": [
    {
        "type": "distinctInstance"
    }
]
```