

# Amazon ECS 任务放置约束示例
<a name="constraint-examples"></a>

下面是一些任务放置约束示例。

此示例使用 `memberOf` 约束在 t2 实例上放置任务。可以使用以下操作指定此约束：[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) 和 [RunTask](https://docs.aws.amazon.com/AmazonECS/latest/APIReference/API_RunTask.html)。

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

该示例使用 `memberOf` 约束将任务放置在进程守护程序服务 `daemon-service` 任务组中具有任务的实例上，同时考虑到同时指定的任何任务放置策略。此约束可确保进程守护程序服务任务在副本服务任务之前放置在 EC2 实例上。

将 `daemon-service` 替换为进程守护程序服务的名称。

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

该示例使用 `memberOf` 约束将任务放置在 `databases` 任务组中具有其他任务的实例上，同时考虑到也指定的任何任务放置策略。有关任务组的更多信息，请参阅 [与组相关的 Amazon ECS 任务](task-groups.md)。可以使用以下操作指定此约束：[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) 和 [RunTask](https://docs.aws.amazon.com/AmazonECS/latest/APIReference/API_RunTask.html)。

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

`distinctInstance` 约束将组中的每项任务放置于不同实例上。可以使用以下操作指定此约束：[CreateService](https://docs.aws.amazon.com/AmazonECS/latest/APIReference/API_CreateService.html)、[UpdateService](https://docs.aws.amazon.com/AmazonECS/latest/APIReference/API_UpdateService.html) 和 [RunTask](https://docs.aws.amazon.com/AmazonECS/latest/APIReference/API_RunTask.html)。

Amazon ECS 会检查所需的任务状态以放置任务。例如，假设现有任务所需的状态为 `STOPPED`（但最近的状态不是该状态），则可以将新传入的任务放入同一个实例，尽管存在 `distinctInstance` 放置约束。因此，您可能会看到同一个实例上有 2 个任务最近的状态都为 `RUNNING`。

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