

# How Amazon ECS places tasks on container instances
<a name="task-placement"></a>

You can use task placement to configure Amazon ECS to place your tasks on container instances that meet certain criteria, for example an Availability Zone or instance type.

The following are task placement components:
+ Task placement strategy - The algorithm for selecting container instances for task placement or tasks for termination. For example, Amazon ECS can select container instances at random, or it can select container instances such that tasks are distributed evenly across a group of instances.
+ Task group - A group of related tasks, for example database tasks.
+ Task placement constraint - These are rules that must be met in order to place a task on a container instance. If the constraint is not met, the task is not placed and remains in the `PENDING` state. For example, you can use a constraint to place tasks only on a particular instance type. 

Amazon ECS has different algorithms for the different capacity options. 

## Amazon ECS Managed Instances
<a name="managed-instances-launch-type"></a>

For tasks that run on Amazon ECS Managed Instances, Amazon ECS must determine where to place the task, and — when scaling down task count — which tasks to terminate. Amazon ECS makes this determination based on the instance requirements specified in the capacity provider launch template, requirements specified in the task definition such as CPU and memory, and task placement constraints.

**Note**  
Amazon ECS Managed Instances does not support task placement strategies. Amazon ECS will try its best to spread tasks across accessible Availability Zones.

When Amazon ECS places tasks, it uses the following process to select container instances:

1. Identify the container instances that satisfy the CPU, GPU, memory, and port requirements in the task definition.

1. Identify the container instances that satisfy the task placement constraints.

1. Identify the container instances that satisfy the instance requirements specified in the capacity provider launch template.

1. Select the container instances for task placement.

## EC2
<a name="ec2-launch-type"></a>

For tasks that use the EC2 launch type, Amazon ECS must determine where to place the task based on the requirements specified in the task definition, such as CPU and memory. Similarly, when you scale down the task count, Amazon ECS must determine which tasks to terminate. You can apply task placement strategies and constraints to customize how Amazon ECS places and terminates tasks. 

The default task placement strategies depend on whether you run tasks manually (standalone tasks) or within a service. For tasks running as part of an Amazon ECS service, the task placement strategy is `spread` using the `attribute:ecs.availability-zone`. There isn't a default task placement constraint for tasks not in services. For more information, see [Schedule your containers on Amazon ECS](scheduling_tasks.md).

**Note**  
Task placement strategies are a best effort. Amazon ECS still attempts to place tasks even when the most optimal placement option is unavailable. However, task placement constraints are binding, and they can prevent task placement. 

You can use task placement strategies and constraints together. For example, you can use a task placement strategy and a task placement constraint to distribute tasks across Availability Zones and bin pack tasks based on memory within each Availability Zone, but only for G2 instances.

When Amazon ECS places tasks, it uses the following process to select container instances:

1. Identify the container instances that satisfy the CPU, GPU, memory, and port requirements in the task definition.

1. Identify the container instances that satisfy the task placement constraints.

1. Identify the container instances that satisfy the task placement strategies.

1. Select the container instances for task placement.

## Fargate
<a name="fargate-launch-type"></a>

Task placement strategies and constraints aren't supported for tasks using the Fargate. Fargate will try its best to spread tasks across accessible Availability Zones. If the capacity provider includes both Fargate and Fargate Spot, the spread behavior is independent for each capacity provider. 

# Amazon ECS Managed Instances auto scaling and task placement
<a name="managed-instance-auto-scaling"></a>

Amazon ECS Managed Instances use intelligent algorithms to automatically scale your cluster capacity and place tasks efficiently across your infrastructure. Understanding how these algorithms work helps you optimize your service configurations and troubleshoot placement behaviors.

## Task placement algorithm
<a name="managed-instance-task-placement-algorithm"></a>

Amazon ECS Managed Instances use a sophisticated placement algorithm that balances availability, resource utilization, and network requirements when scheduling tasks.

### Availability Zone spread
<a name="managed-instance-az-spread-behavior"></a>

By default, Amazon ECS Managed Instances prioritize availability by spreading tasks across multiple Availability Zones:
+ For services with multiple tasks, Amazon ECS Managed Instances ensure distribution across at least 3 instances in different Availability Zones when possible
+ This behavior provides fault tolerance but may result in lower resource utilization per instance
+ Availability Zone spread takes precedence over bin packing optimization

### Bin packing behavior
<a name="managed-instance-bin-packing"></a>

While Amazon ECS Managed Instances can perform bin packing to maximize resource utilization, this behavior is influenced by your network configuration:
+ To achieve bin packing, configure your service to use a single subnet
+ Multi-subnet configurations prioritize Availability Zone distribution over resource density
+ Bin packing is more likely during initial service launch than during scaling events

### ENI density considerations
<a name="managed-instance-eni-density"></a>

For services using the `awsvpc` network mode, Amazon ECS Managed Instances consider Elastic Network Interface (ENI) density when making placement decisions:
+ Each task in `awsvpc` mode requires a dedicated ENI
+ Instance types have different ENI limits that affect task density
+ Amazon ECS Managed Instances account for ENI availability when selecting target instances

**Note**  
Improvements to ENI density calculations are continuously being made to optimize placement decisions.

## Capacity provider decision logic
<a name="managed-instance-capacity-provider-decisions"></a>

Amazon ECS Managed Instances capacity providers make scaling and placement decisions based on multiple factors:

Resource requirements  
CPU, memory, and network requirements of pending tasks

Instance availability  
Current capacity and utilization across existing instances

Network constraints  
Subnet configuration and ENI availability

Availability Zone distribution  
Maintaining fault tolerance across multiple Availability Zones

## Configuration options
<a name="managed-instance-configuration-options"></a>

### Subnet selection strategy
<a name="managed-instance-subnet-strategy"></a>

Your subnet configuration significantly impacts task placement behavior:

Multiple subnets (default)  
Prioritizes Availability Zone spread for high availability  
May result in lower resource utilization per instance  
Recommended for production workloads requiring fault tolerance

Single subnet  
Enables bin packing for higher resource utilization  
Reduces fault tolerance by concentrating tasks in one Availability Zone  
Suitable for development or cost-optimized workloads

### Network mode considerations
<a name="managed-instance-network-mode-considerations"></a>

The network mode you choose affects placement decisions:
+ `awsvpc` mode – Each task requires a dedicated ENI, limiting task density per instance
+ `host` mode – Tasks use the host's network directly, with placement primarily driven by resource availability

### CPU architecture considerations
<a name="managed-instance-cpu-architecture-considerations"></a>

The `cpuArchitecture` that you specify in your task definition is used for placing tasks on a specific architecture. If you don't specify a `cpuArchitecture`, Amazon ECS will try to place tasks on any available CPU architecture based on the capacity provider configuration. You can specify either `X86_64` or `ARM64`.

## Troubleshooting task placement
<a name="managed-instance-troubleshooting-placement"></a>

### Common placement patterns
<a name="managed-instance-common-placement-patterns"></a>

Understanding expected placement patterns helps distinguish normal behavior from potential issues:

Spread distribution  
Tasks distributed across multiple instances with partial utilization  
Normal behavior when using multiple subnets  
Indicates prioritization of availability over resource efficiency

Concentrated placement  
Multiple tasks placed on fewer instances with higher utilization  
Expected when using single subnet configuration  
May occur during initial service launch

Uneven distribution  
Some instances heavily utilized while others remain underutilized  
May indicate ENI limits or resource constraints  
Consider reviewing instance types and network configuration

### Optimizing placement behavior
<a name="managed-instance-placement-optimization"></a>

To optimize task placement for your specific requirements:

1. Evaluate your availability requirements versus cost optimization needs

1. Choose appropriate subnet configuration based on your priorities

1. Select instance types with adequate ENI capacity for your network mode

1. Monitor placement patterns and adjust configuration as needed

## Best practices
<a name="managed-instance-best-practices"></a>
+ **For production workloads** – Use multiple subnets across different Availability Zones to ensure high availability, accepting the trade-off in resource utilization
+ **For development or testing** – Consider single subnet configuration to maximize resource utilization and reduce costs
+ **For `awsvpc` mode** – Choose instance types with sufficient ENI capacity to avoid placement constraints
+ **For cost optimization** – Monitor utilization patterns and adjust service configuration to balance availability and efficiency
+ **For troubleshooting** – Review subnet configuration and network mode when investigating unexpected placement patterns

# Use strategies to define Amazon ECS task placement
<a name="task-placement-strategies"></a>

For tasks that use the EC2 launch type, Amazon ECS must determine where to place the task based on the requirements specified in the task definition, such as CPU and memory. Similarly, when you scale down the task count, Amazon ECS must determine which tasks to terminate. You can apply task placement strategies and constraints to customize how Amazon ECS places and terminates tasks. 

The default task placement strategies depend on whether you run tasks manually (standalone tasks) or within a service. For tasks running as part of an Amazon ECS service, the task placement strategy is `spread` using the `attribute:ecs.availability-zone`. There isn't a default task placement constraint for tasks not in services. For more information, see [Schedule your containers on Amazon ECS](scheduling_tasks.md).

**Note**  
Task placement strategies are a best effort. Amazon ECS still attempts to place tasks even when the most optimal placement option is unavailable. However, task placement constraints are binding, and they can prevent task placement. 

You can use task placement strategies and constraints together. For example, you can use a task placement strategy and a task placement constraint to distribute tasks across Availability Zones and bin pack tasks based on memory within each Availability Zone, but only for G2 instances.

When Amazon ECS places tasks, it uses the following process to select container instances:

1. Identify the container instances that satisfy the CPU, GPU, memory, and port requirements in the task definition.

1. Identify the container instances that satisfy the task placement constraints.

1. Identify the container instances that satisfy the task placement strategies.

1. Select the container instances for task placement.

You specify task placement strategies in the service definition, or task definition using the `placementStrategy` parameter.

```
"placementStrategy": [
    {
        "field": "The field to apply the placement strategy against",
        "type": "The placement strategy to use"
    }
]
```

You can specify the strategies when you run a task ([RunTask](https://docs.aws.amazon.com/AmazonECS/latest/APIReference/API_RunTask.html)), create a new service ( [CreateService](https://docs.aws.amazon.com/AmazonECS/latest/APIReference/API_CreateService.html)), or update an existing service ([UpdateService](https://docs.aws.amazon.com/AmazonECS/latest/APIReference/API_UpdateService.html)).

The following table describes the available types and fields.


| type | Valid field values | 
| --- | --- | 
| binpack Tasks are placed on container instances so as to leave the least amount of unused CPU or memory. This strategy minimizes the number of container instances in use. When this strategy is used and a scale-in action is taken, Amazon ECS terminates tasks. It does this based on the amount of resources that are left on the container instance after the task is terminated. The container instance that has the most available resources left after task termination has that task terminated. |  [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/AmazonECS/latest/developerguide/task-placement-strategies.html)  | 
| random Tasks are placed randomly. | Not used | 
| spreadTasks are placed evenly based on the specified value. Service tasks are spread based on the tasks from that service. Standalone tasks are spread based on the tasks from the same task group. For more information about task groups, see [Group related Amazon ECS tasks](task-groups.md). When the `spread` strategy is used and a scale-in action is taken, Amazon ECS selects tasks to terminate that maintain a balance across Availability Zones. Within an Availability Zone, tasks are selected at random. |  [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/AmazonECS/latest/developerguide/task-placement-strategies.html)  | 

The task placement strategies can be updated for existing services as well. For more information, see [How Amazon ECS places tasks on container instances](task-placement.md).

You can create a task placement strategy that uses multiple strategies by creating arrays of strategies in the order that you want them performed. For example, if you want to spread tasks across Availability Zones and then bin pack tasks based on memory within each Availability Zone, specify the Availability Zone strategy followed by the memory strategy. For example strategies, see [Example Amazon ECS task placement strategies](strategy-examples.md).

# Example Amazon ECS task placement strategies
<a name="strategy-examples"></a>

You can specify task placement strategies 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).

**Topics**
+ [

## Distribute tasks evenly across Availability Zones
](#even-az)
+ [

## Distribute tasks evenly across all instances
](#even-instance)
+ [

## Bin pack tasks based on memory
](#binpack)
+ [

## Place tasks randomly
](#random)
+ [

## Distribute tasks evenly across Availability Zones and then distributes tasks evenly across the instances within each Availability Zone
](#az-instance)
+ [

## Distribute tasks evenly across Availability Zones and then bin pack tasks based on memory within each Availability Zone
](#az-memory)
+ [

## Distribute tasks evenly across instances and then bin pack tasks based on memory
](#instance-memory)

## Distribute tasks evenly across Availability Zones
<a name="even-az"></a>

The following strategy distributes tasks evenly across Availability Zones.

```
"placementStrategy": [
    {
        "field": "attribute:ecs.availability-zone",
        "type": "spread"
    }
]
```

## Distribute tasks evenly across all instances
<a name="even-instance"></a>

The following strategy distributes tasks evenly across all instances.

```
"placementStrategy": [
    {
        "field": "instanceId",
        "type": "spread"
    }
]
```

## Bin pack tasks based on memory
<a name="binpack"></a>

The following strategy bin packs tasks based on memory.

```
"placementStrategy": [
    {
        "field": "memory",
        "type": "binpack"
    }
]
```

## Place tasks randomly
<a name="random"></a>

The following strategy places tasks randomly.

```
"placementStrategy": [
    {
        "type": "random"
    }
]
```

## Distribute tasks evenly across Availability Zones and then distributes tasks evenly across the instances within each Availability Zone
<a name="az-instance"></a>

The following strategy distributes tasks evenly across Availability Zones and then distributes tasks evenly across the instances within each Availability Zone.

```
"placementStrategy": [
    {
        "field": "attribute:ecs.availability-zone",
        "type": "spread"
    },
    {
        "field": "instanceId",
        "type": "spread"
    }
]
```

## Distribute tasks evenly across Availability Zones and then bin pack tasks based on memory within each Availability Zone
<a name="az-memory"></a>

The following strategy distributes tasks evenly across Availability Zones and then bin packs tasks based on memory within each Availability Zone.

```
"placementStrategy": [
    {
        "field": "attribute:ecs.availability-zone",
        "type": "spread"
    },
    {
        "field": "memory",
        "type": "binpack"
    }
]
```

## Distribute tasks evenly across instances and then bin pack tasks based on memory
<a name="instance-memory"></a>

The following strategy distributes tasks evenly across evenly across all instances and then bin packs tasks based on memory within each instance. 

```
"placementStrategy": [
    {
        "field": "instanceId",
        "type": "spread"
    },
    {
        "field": "memory",
        "type": "binpack"
    }
]
```

# Group related Amazon ECS tasks
<a name="task-groups"></a>

You can identify a set of related tasks and place them in a task group. All tasks with the same task group name are considered as a set when using the `spread` task placement strategy. For example, suppose that you're running different applications in one cluster, such as databases and web servers. To ensure that your databases are balanced across Availability Zones, add them to a task group named `databases` and then use the `spread` task placement strategy. For more information, see [Use strategies to define Amazon ECS task placement](task-placement-strategies.md).

Task groups can also be used as a task placement constraint. When you specify a task group in the `memberOf` constraint, tasks are only sent to container instances that run tasks in the specified task group. For an example, see [Example Amazon ECS task placement constraints](constraint-examples.md).

By default, standalone tasks use the task definition family name (for example, `family:my-task-definition`) as the task group name if a custom task group name isn't specified. Tasks launched as part of a service use the service name as the task group name and can't be changed.

The following requirements for the task group apply.
+ A task group name must be 255 or fewer characters.
+ Each task can be in exactly one group.
+ After launching a task, you can't modify its task group.

# Define which container instances Amazon ECS uses for tasks
<a name="task-placement-constraints"></a>

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
<a name="attributes"></a>

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
<a name="ecs-automatic-attributes"></a>

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
<a name="ecs-optional-attributes"></a>

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
<a name="ecs-custom-attributes"></a>

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
<a name="cluster-query-language"></a>

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
<a name="expression-syntax"></a>

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
<a name="expression-examples"></a>

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
<a name="constraint-examples"></a>

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"
    }
]
```