

# 使用 Amazon CLI 为 Fargate 创建 Amazon ECS Windows 任务
<a name="ECS_AWSCLI_Fargate_windows"></a>

以下步骤帮助您在 Amazon ECS 中使用 Amazon CLI 设置集群、注册任务定义、运行 Windows 任务和执行其他常见方案。请确保您使用的是最新版本的 Amazon CLI。有关如何升级到最新版本的更多信息，请参阅[安装或更新到最新版本的 Amazon CLI](https://docs.amazonaws.cn/cli/latest/userguide/getting-started-install.html)。

**注意**  
您可以使用双堆栈服务端点通过 IPv4 和 IPv6 从 Amazon CLI、SDK 和 Amazon ECS API 与 Amazon ECS 进行交互。有关更多信息，请参阅 [使用 Amazon ECS 双堆栈端点](dual-stack-endpoint.md)。

**Topics**
+ [先决条件](#ECS_AWSCLI_Fargate_windows_prereq)
+ [步骤 1：创建集群](#ECS_AWSCLI_Fargate_windows_create_cluster)
+ [步骤 2：注册 Windows 任务定义](#ECS_AWSCLI_Fargate_windows_register_task_definition)
+ [步骤 3：列出任务定义](#ECS_AWSCLI_Fargate_windows__list_task_definitions)
+ [步骤 4：创建服务](#ECS_AWSCLI_Fargate_windows_create_service)
+ [步骤 5：列出服务](#ECS_AWSCLI_Fargate_windows_list_services)
+ [步骤 6：描述正在运行的服务](#ECS_AWSCLI_Fargate_windows_describe_service)
+ [步骤 7：清理](#ECS_AWSCLI_Fargate_windows_clean_up)

## 先决条件
<a name="ECS_AWSCLI_Fargate_windows_prereq"></a>

本教程假设以下先决条件已完成。
+ 安装并配置了最新版本的 Amazon CLI。有关安装或升级 Amazon CLI 的更多信息，请参阅 [Installing or updating to the latest version of the Amazon CLI](https://docs.amazonaws.cn/cli/latest/userguide/getting-started-install.html)。
+ [设置以使用 Amazon ECS](get-set-up-for-amazon-ecs.md) 中的步骤已完成。
+ 您的 IAM 用户具有 [AmazonECS\$1FullAccess](security-iam-awsmanpol.md#security-iam-awsmanpol-AmazonECS_FullAccess) IAM 策略示例中指定的必需权限。
+ 您已创建要使用的 VPC 和安全组。本教程使用的是托管在 Docker Hub 上的容器映像，因此，您的任务必须具有互联网访问权限。要让您的任务连接到互联网，请使用下列选项之一。
  + 将私有子网与具有弹性 IP 地址的 NAT 网关结合使用。
  + 使用公有子网并向任务分配公有 IP 地址。

  有关更多信息，请参阅 [创建虚拟私有云](get-set-up-for-amazon-ecs.md#create-a-vpc)。

  有关安全组的信息，请参阅**《Amazon Virtual Private Cloud 用户指南》中的 [VPC 的默认安全组](https://docs.amazonaws.cn/vpc/latest/userguide/VPC_SecurityGroups.html#DefaultSecurityGroup)和[示例规则](https://docs.amazonaws.cn/vpc/latest/userguide/VPC_SecurityGroups.html#security-group-rule-examples)。
+ （可选）Amazon CloudShell 是一种为客户提供命令行的工具，而无需创建自己的 EC2 实例。有关更多信息，请参阅《Amazon CloudShell 用户指南》**中的[什么是 Amazon CloudShell？](https://docs.amazonaws.cn/cloudshell/latest/userguide/welcome.html)。

## 步骤 1：创建集群
<a name="ECS_AWSCLI_Fargate_windows_create_cluster"></a>

默认情况下，您的账户会收到一个 `default` 集群。

**注意**  
使用为您提供的 `default` 集群的好处是您不必在后续命令中指定 `--cluster cluster_name` 选项。如果您自行创建非默认集群，您必须为您打算用于该集群的每个命令指定 `--cluster cluster_name`。

使用以下命令自行创建具有唯一名称的集群：

```
aws ecs create-cluster --cluster-name fargate-cluster
```

输出：

```
{
    "cluster": {
        "status": "ACTIVE", 
        "statistics": [], 
        "clusterName": "fargate-cluster", 
        "registeredContainerInstancesCount": 0, 
        "pendingTasksCount": 0, 
        "runningTasksCount": 0, 
        "activeServicesCount": 0, 
        "clusterArn": "arn:aws:ecs:region:aws_account_id:cluster/fargate-cluster"
    }
}
```

## 步骤 2：注册 Windows 任务定义
<a name="ECS_AWSCLI_Fargate_windows_register_task_definition"></a>

您必须先注册任务定义才能在 Amazon ECS 集群上运行 Windows 任务。任务定义是分组在一起的一系列容器。下面的示例是创建 Web 应用程序的一个简单任务定义。有关可用任务定义参数的更多信息，请参阅 [Amazon ECS 任务定义](task_definitions.md)。

```
{
    "containerDefinitions": [
        {
            "command": ["New-Item -Path C:\\inetpub\\wwwroot\\index.html -Type file -Value '<html> <head> <title>Amazon ECS Sample App</title> <style>body {margin-top: 40px; background-color: #333;} </style> </head><body> <div style=color:white;text-align:center> <h1>Amazon ECS Sample App</h1> <h2>Congratulations!</h2> <p>Your application is now running on a container in Amazon ECS.</p>'; C:\\ServiceMonitor.exe w3svc"],
            "entryPoint": [
                "powershell",
                "-Command"
            ],
            "essential": true,
            "cpu": 2048,
            "memory": 4096,
            "image": "mcr.microsoft.com/windows/servercore/iis:windowsservercore-ltsc2019",
            "name": "sample_windows_app",
            "portMappings": [
                {
                    "hostPort": 80,
                    "containerPort": 80,
                    "protocol": "tcp"
                }
            ]
        }
    ],
    "memory": "4096",
    "cpu": "2048",
    "networkMode": "awsvpc",
    "family": "windows-simple-iis-2019-core",
    "executionRoleArn": "arn:aws:iam::012345678910:role/ecsTaskExecutionRole",
    "runtimePlatform": {"operatingSystemFamily": "WINDOWS_SERVER_2019_CORE"},
    "requiresCompatibilities": ["FARGATE"]
}
```

上述示例 JSON 可通过两种方式传递到 Amazon CLI：您可以将任务定义 JSON 保存为文件并使用 `--cli-input-json file://path_to_file.json` 选项传递它。

将 JSON 文件用于容器定义：

```
aws ecs register-task-definition --cli-input-json file://$HOME/tasks/fargate-task.json
```

**register-task-definition** 命令在完成其注册后会返回任务定义的描述。

## 步骤 3：列出任务定义
<a name="ECS_AWSCLI_Fargate_windows__list_task_definitions"></a>

您可以随时使用 **list-task-definitions** 命令列出您的账户的任务定义。此命令的输出将显示 `family` 和 `revision` 值，您可以在调用 **run-task** 或 **start-task** 时将这些值一起使用。

```
aws ecs list-task-definitions
```

输出：

```
{
    "taskDefinitionArns": [
        "arn:aws:ecs:region:aws_account_id:task-definition/sample-fargate-windows:1"
    ]
}
```

## 步骤 4：创建服务
<a name="ECS_AWSCLI_Fargate_windows_create_service"></a>

为账户注册任务后，您可以为集群中已注册的任务创建服务。在此示例中，您将使用集群中运行的一个 `sample-fargate:1` 任务定义实例来创建服务。此任务需要连接到互联网，您可以通过两种方法实现这一点。一种方法是将使用 NAT 网关配置的私有子网与公有子网中的弹性 IP 地址结合使用。另一种方法是使用公有子网并向任务分配公有 IP 地址。下面提供了这两种方法的示例。

使用私有子网的示例。

```
aws ecs create-service --cluster fargate-cluster --service-name fargate-service --task-definition sample-fargate-windows:1 --desired-count 1 --launch-type "FARGATE" --network-configuration "awsvpcConfiguration={subnets=[subnet-abcd1234],securityGroups=[sg-abcd1234]}"
```

使用公有子网的示例。

```
aws ecs create-service --cluster fargate-cluster --service-name fargate-service --task-definition sample-fargate-windows:1 --desired-count 1 --launch-type "FARGATE" --network-configuration "awsvpcConfiguration={subnets=[subnet-abcd1234],securityGroups=[sg-abcd1234],assignPublicIp=ENABLED}"
```

**create-service** 命令在完成其注册后会返回任务定义的描述。

## 步骤 5：列出服务
<a name="ECS_AWSCLI_Fargate_windows_list_services"></a>

列出您的集群的服务。您应看到您在上一部分中创建的服务。您可以选取从此命令返回的服务名称或完整 ARN 并在稍后将其用于描述服务。

```
aws ecs list-services --cluster fargate-cluster
```

输出：

```
{
    "serviceArns": [
        "arn:aws:ecs:region:aws_account_id:service/fargate-service"
    ]
}
```

## 步骤 6：描述正在运行的服务
<a name="ECS_AWSCLI_Fargate_windows_describe_service"></a>

使用之前检索到的服务名称描述服务，以获取有关任务的更多信息。

```
aws ecs describe-services --cluster fargate-cluster --services fargate-service
```

如果成功，这将返回服务失败和服务的描述。例如，在服务部分中，您将找到有关部署的信息，例如任务的正在运行或待处理状态。也可以找到有关任务定义、网络配置和带时间戳的事件的信息。在失败部分中，您将找到与调用关联的失败的信息（如果有）。对于问题排查，请参阅[服务事件消息](https://docs.amazonaws.cn/AmazonECS/latest/developerguide/service-event-messages.html)。有关服务描述的更多信息，请参阅[描述服务](https://docs.amazonaws.cn/AmazonECS/latest/APIReference/API_DescribeServices)。

```
{
    "services": [
        {
            "status": "ACTIVE", 
            "taskDefinition": "arn:aws:ecs:region:aws_account_id:task-definition/sample-fargate-windows:1", 
            "pendingCount": 2, 
            "launchType": "FARGATE", 
            "loadBalancers": [], 
            "roleArn": "arn:aws:iam::aws_account_id:role/aws-service-role/ecs.amazonaws.com/AWSServiceRoleForECS", 
            "placementConstraints": [], 
            "createdAt": 1510811361.128, 
            "desiredCount": 2, 
            "networkConfiguration": {
                "awsvpcConfiguration": {
                    "subnets": [
                        "subnet-abcd1234"
                    ], 
                    "securityGroups": [
                        "sg-abcd1234"
                    ], 
                    "assignPublicIp": "DISABLED"
                }
            }, 
            "platformVersion": "LATEST", 
            "serviceName": "fargate-service", 
            "clusterArn": "arn:aws:ecs:region:aws_account_id:cluster/fargate-cluster", 
            "serviceArn": "arn:aws:ecs:region:aws_account_id:service/fargate-service", 
            "deploymentConfiguration": {
                "maximumPercent": 200, 
                "minimumHealthyPercent": 100
            }, 
            "deployments": [
                {
                    "status": "PRIMARY", 
                    "networkConfiguration": {
                        "awsvpcConfiguration": {
                            "subnets": [
                                "subnet-abcd1234"
                            ], 
                            "securityGroups": [
                                "sg-abcd1234"
                            ], 
                            "assignPublicIp": "DISABLED"
                        }
                    }, 
                    "pendingCount": 2, 
                    "launchType": "FARGATE", 
                    "createdAt": 1510811361.128, 
                    "desiredCount": 2, 
                    "taskDefinition": "arn:aws:ecs:region:aws_account_id:task-definition/sample-fargate-windows:1", 
                    "updatedAt": 1510811361.128, 
                    "platformVersion": "0.0.1", 
                    "id": "ecs-svc/9223370526043414679", 
                    "runningCount": 0
                }
            ], 
            "events": [
                {
                    "message": "(service fargate-service) has started 2 tasks: (task 53c0de40-ea3b-489f-a352-623bf1235f08) (task d0aec985-901b-488f-9fb4-61b991b332a3).", 
                    "id": "92b8443e-67fb-4886-880c-07e73383ea83", 
                    "createdAt": 1510811841.408
                }, 
                {
                    "message": "(service fargate-service) has started 2 tasks: (task b4911bee-7203-4113-99d4-e89ba457c626) (task cc5853e3-6e2d-4678-8312-74f8a7d76474).", 
                    "id": "d85c6ec6-a693-43b3-904a-a997e1fc844d", 
                    "createdAt": 1510811601.938
                }, 
                {
                    "message": "(service fargate-service) has started 2 tasks: (task cba86182-52bf-42d7-9df8-b744699e6cfc) (task f4c1ad74-a5c6-4620-90cf-2aff118df5fc).", 
                    "id": "095703e1-0ca3-4379-a7c8-c0f1b8b95ace", 
                    "createdAt": 1510811364.691
                }
            ], 
            "runningCount": 0, 
            "placementStrategy": []
        }
    ], 
    "failures": []
}
```

## 步骤 7：清理
<a name="ECS_AWSCLI_Fargate_windows_clean_up"></a>

完成本教程后，您应清除相关资源，以避免产生与未使用的资源相关的费用。

删除服务。

```
aws ecs delete-service --cluster fargate-cluster --service fargate-service --force
```

请删除集群。

```
aws ecs delete-cluster --cluster fargate-cluster
```