

本文為英文版的機器翻譯版本，如內容有任何歧義或不一致之處，概以英文版為準。

# 了解如何使用 為 Amazon ECS 受管執行個體建立任務 AWS CLI
<a name="getting-started-managed-instances-cli"></a>

 下列步驟會協助您使用 AWS CLI在 Amazon ECS 中搭配 Amazon ECS 受管執行個體設定叢集、建立容量提供者、註冊任務定義、執行 Linux 任務以及執行其他常見案例。使用 AWS CLI的最新版本。如需有關如何升級至最新版本的詳細資訊，請參閱 [Installing or updating to the latest version of the AWS CLI](https://docs.aws.amazon.com/cli/latest/userguide/getting-started-install.html)。

**注意**  
 您可以使用雙堆疊服務端點，透過 IPv4 和 IPv6 從 AWS AWS CLI、SDK 和 Amazon ECS API 與 Amazon ECS 互動。如需詳細資訊，請參閱[使用 Amazon ECS 雙堆疊端點](dual-stack-endpoint.md)。

**主題**
+ [先決條件](#managed-instances-cli-prereq)
+ [步驟 1：建立叢集](#managed-instances-cli-create-cluster)
+ [步驟 2：建立 Amazon ECS 受管執行個體容量提供者](#managed-instances-cli-create-capacity-provider)
+ [步驟 3：設定叢集的預設容量提供者策略](#managed-instances-cli-configure-cluster)
+ [步驟 4：註冊 Linux 任務定義](#managed-instances-cli-register-task-definition)
+ [步驟 5：列出任務定義](#managed-instances-cli-list-task-definitions)
+ [步驟 6：建立服務](#managed-instances-cli-create-service)
+ [步驟 7：列出服務](#managed-instances-cli-list-services)
+ [步驟 8：描述正在執行中的服務](#managed-instances-cli-describe-service)
+ [步驟 9：測試](#managed-instances-cli-test)
+ [步驟 10：清除](#managed-instances-cli-clean-up)

## 先決條件
<a name="managed-instances-cli-prereq"></a>

 開始本教學之前，先完成下列動作：
+ 您已完成[設定使用 Amazon ECS](https://docs.aws.amazon.com/AmazonECS/latest/developerguide/get-set-up-for-amazon-ecs.html) 一節中的步驟。
+  AWS CLI 已安裝並設定最新版本的 。如需安裝或升級 的詳細資訊 AWS CLI，請參閱*AWS Command Line Interface 《 使用者指南*》中的[安裝或更新至最新版本的 AWS CLI](https://docs.aws.amazon.com/cli/latest/userguide/getting-started-install.html)。
+ 已完成「[設定以使用 Amazon ECS。](get-set-up-for-amazon-ecs.md)」中的步驟。
+ 您有 Amazon ECS 受管執行個體所需的 IAM 角色。其中包含：
  + 基礎設施角色 - 允許 Amazon ECS 代表您呼叫 AWS 服務，以管理 Amazon ECS 受管執行個體基礎設施。

    如需詳細資訊，請參閱[Amazon ECS 基礎結構 IAM 角色](infrastructure_IAM_role.md)。
  + 執行個體設定檔 – 為在受管執行個體上執行的 Amazon ECS 容器代理程式與 Docker 常駐程式提供許可。

    執行個體角色名稱必須包含 `ecsInstanceRole`做為字首，以符合基礎設施角色中的`iam:PassRole`動作。

    如需詳細資訊，請參閱[Amazon ECS 受管執行個體執行個體設定檔](managed-instances-instance-profile.md)。
+ 您已建立 VPC 和安全群組。本教學課程使用託管於 Amazon ECR Public 的容器映像，因此您的執行個體必須有網際網路存取權。若要將網際網路的路由提供給執行個體，請使用下列其中一個選項：
  + 透過具有彈性 IP 地址的 NAT 閘道使用私有子網路。
  + 使用公有子網路，並將公有 IP 位址指派給執行個體。

  如需詳細資訊，請參閱[建立 Virtual Private Cloud](get-set-up-for-amazon-ecs.md#create-a-vpc)。

  如需有關安全群組與規則的資訊，請參閱 *Amazon Virtual Private Cloud User Guide* 中的 [Default security groups for your VPCs](https://docs.aws.amazon.com/vpc/latest/userguide/VPC_SecurityGroups.html#DefaultSecurityGroup) 和 [Example rules](https://docs.aws.amazon.com/vpc/latest/userguide/VPC_SecurityGroups.html#security-group-rule-examples)。
+ （選用） AWS CloudShell 是一種工具，可為客戶提供命令列，而不需要建立自己的 EC2 執行個體。如需詳細資訊，請參閱[什麼是 AWS CloudShell？](https://docs.aws.amazon.com/cloudshell/latest/userguide/welcome.html) 《*AWS CloudShell 使用者指南*》中的 。

## 步驟 1：建立叢集
<a name="managed-instances-cli-create-cluster"></a>

 您的帳戶預設會得到 `default` 叢集。

**注意**  
 使用為您提供之 `default` 叢集的優點是，您不必在後續的命令中指定 `--cluster cluster_name` 選項。如果您建立的是自己的叢集，不是預設叢集，您必須在打算對該叢集使用的每個命令中指定 `--cluster cluster_name`。

 使用下列命令以唯一的名稱建立您自己的叢集：

```
aws ecs create-cluster --cluster-name managed-instances-cluster
```

輸出：

```
{
    "cluster": {
        "status": "ACTIVE", 
        "defaultCapacityProviderStrategy": [], 
        "statistics": [], 
        "capacityProviders": [], 
        "tags": [], 
        "clusterName": "managed-instances-cluster", 
        "settings": [
            {
                "name": "containerInsights", 
                "value": "disabled"
            }
        ], 
        "registeredContainerInstancesCount": 0, 
        "pendingTasksCount": 0, 
        "runningTasksCount": 0, 
        "activeServicesCount": 0, 
        "clusterArn": "arn:aws:ecs:region:aws_account_id:cluster/managed-instances-cluster"
    }
}
```

## 步驟 2：建立 Amazon ECS 受管執行個體容量提供者
<a name="managed-instances-cli-create-capacity-provider"></a>

 您必須先建立容量提供者來定義基礎結構組態，才能使用 Amazon ECS 受管執行個體執行任務。容量提供者會為受管執行個體指定 IAM 角色、網路組態以及其他設定。

 使用容量提供者組態建立 JSON 檔案。使用您的實際資源識別碼取代預留位置的值：

```
{
    "name": "managed-instances-cp",
    "cluster": "managed-instances-cluster",
    "managedInstancesProvider": {
        "infrastructureRoleArn": "arn:aws:iam::aws_account_id:role/ecsInfrastructureRole",
        "instanceLaunchTemplate": {
            "ec2InstanceProfileArn": "arn:aws:iam::aws_account_id:instance-profile/ecsInstanceRole",
            "networkConfiguration": {
                "subnets": [
                    "subnet-abcdef01234567890",
                    "subnet-1234567890abcdef0"
                ],
                "securityGroups": [
                    "sg-0123456789abcdef0"
                ]
            },
            "storageConfiguration": {
                "storageSizeGiB": 100
            },
            "monitoring": "basic"
        }
    }
}
```

 將此組態儲存為 `managed-instances-cp.json` 並建立容量提供者：

```
aws ecs create-capacity-provider --cli-input-json file://managed-instances-cp.json
```

 該命令會在容量提供者建立完成後傳回其描述。

## 步驟 3：設定叢集的預設容量提供者策略
<a name="managed-instances-cli-configure-cluster"></a>

 更新叢集以使用 Amazon ECS 受管執行個體容量提供者作為預設容量提供者策略。這可讓任務和服務自動使用 Amazon ECS 受管執行個體，而無需明確指定容量提供者。

 使用叢集容量提供者組態建立 JSON 檔案：

```
{
    "cluster": "managed-instances-cluster",
    "capacityProviders": [
        "managed-instances-cp"
    ],
    "defaultCapacityProviderStrategy": [
        {
            "capacityProvider": "managed-instances-cp",
            "weight": 1
        }
    ]
}
```

 將此組態儲存為 `cluster-cp-strategy.json` 並更新叢集：

```
aws ecs put-cluster-capacity-providers --cli-input-json file://cluster-cp-strategy.json
```

## 步驟 4：註冊 Linux 任務定義
<a name="managed-instances-cli-register-task-definition"></a>

 您必須先註冊任務定義，才能在您的叢集上執行任務。任務定義是分在一組的容器清單。下列範例是使用託管於 Docker Hub 的 httpd 容器映像來建立 PHP Web 應用程式的簡單任務定義。如需可用之任務定義參數的詳細資訊，請參閱「[Fargate 的 Amazon ECS 任務定義參數](task_definition_parameters.md)」。

```
{
    "family": "sample-managed-instances",
    "networkMode": "awsvpc",
    "containerDefinitions": [
        {
            "name": "managed-instances-app",
            "image": "public.ecr.aws/docker/library/httpd:latest",
            "portMappings": [
                {
                    "containerPort": 80,
                    "hostPort": 80,
                    "protocol": "tcp"
                }
            ],
            "essential": true,
            "entryPoint": [
                "sh",
                "-c"
            ],
            "command": [
                "/bin/sh -c \"echo '<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 using Amazon ECS Managed Instances.</p></div></body></html>' >  /usr/local/apache2/htdocs/index.html && httpd-foreground\""
            ]
        }
    ],
    "requiresCompatibilities": [
        "MANAGED_INSTANCES"
    ],
    "cpu": "256",
    "memory": "512"
}
```

 將任務定義 JSON 儲存為檔案，並使用 `--cli-input-json file://path_to_file.json` 選項進行傳遞。

 將 JSON 檔案用於容器定義中：

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

 **register-task-definition** 命令會在完成註冊後傳回任務定義的描述。

## 步驟 5：列出任務定義
<a name="managed-instances-cli-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-managed-instances:1"
    ]
}
```

## 步驟 6：建立服務
<a name="managed-instances-cli-create-service"></a>

 為您的帳戶註冊任務之後，您就可以在您的叢集中建立已註冊任務的服務。在此範例中，您將透過在叢集中執行之 `sample-managed-instances:1` 任務定義的一個執行個體建立服務。該任務需要網際網路的路由，因此您可透過兩種方法達成。一種方法是，使用透過 NAT 閘道所設定的私有子網路，而該閘道在公有子網路中具有彈性 IP 地址。另一種方法是，使用公有子網路並將公有 IP 地址指派至任務。以下提供這兩種範例。

 使用私有子網路的範例：

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

 使用公有子網路的範例：

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

 **create-service** 命令會在服務建立完成後傳回服務的描述。

## 步驟 7：列出服務
<a name="managed-instances-cli-list-services"></a>

 列出您叢集的服務。您應該會看到您在先前一節所建立的服務。您可以記下這個命令傳回的服務名稱或完整的 ARN，稍後將用以描述服務。

```
aws ecs list-services --cluster managed-instances-cluster
```

輸出：

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

## 步驟 8：描述正在執行中的服務
<a name="managed-instances-cli-describe-service"></a>

 使用之前擷取的服務名稱來描述服務，以取得任務的詳細資訊。

```
aws ecs describe-services --cluster managed-instances-cluster --services managed-instances-service
```

 如果成功，這會傳回服務失敗和服務的描述。例如，在 `services` 區段中，您將可以找到部署的相關資訊，例如執行中或擱置中的任務狀態。您也可以找到任務定義、網路組態和時間戳記事件的相關資訊。在失敗區段中，您將可以找到與呼叫相關聯的失敗 (如果有的話) 的相關資訊。

 輸出將顯示服務正在使用 Amazon ECS 受管執行個體容量提供者：

```
{
    "services": [
        {
            "capacityProviderStrategy": [
                {
                    "capacityProvider": "managed-instances-cp",
                    "weight": 1,
                    "base": 0
                }
            ],
            "networkConfiguration": {
                "awsvpcConfiguration": {
                    "subnets": [
                        "subnet-abcd1234"
                    ], 
                    "securityGroups": [
                        "sg-abcd1234"
                    ], 
                    "assignPublicIp": "ENABLED"
                }
            }, 
            "enableECSManagedTags": false, 
            "loadBalancers": [], 
            "deploymentController": {
                "type": "ECS"
            }, 
            "desiredCount": 1, 
            "clusterArn": "arn:aws:ecs:region:aws_account_id:cluster/managed-instances-cluster", 
            "serviceArn": "arn:aws:ecs:region:aws_account_id:service/managed-instances-service", 
            "serviceName": "managed-instances-service",
            "taskDefinition": "arn:aws:ecs:region:aws_account_id:task-definition/sample-managed-instances:1"
        }
    ], 
    "failures": []
}
```

## 步驟 9：測試
<a name="managed-instances-cli-test"></a>

 若要測試您的部署，您需要找到執行任務之受管執行個體的公有 IP 位址。

### 使用公有子網路部署的測試任務
<a name="managed-instances-cli-test-public-subnet"></a>

 首先，從服務中取得任務 ARN：

```
aws ecs list-tasks --cluster managed-instances-cluster --service managed-instances-service
```

 輸出包含任務 ARN：

```
{
    "taskArns": [
        "arn:aws:ecs:region:aws_account_id:task/managed-instances-cluster/EXAMPLE"
    ]
}
```

 描述任務以取得容器執行個體 ARN。將任務 ARN 用於 `tasks` 參數：

```
aws ecs describe-tasks --cluster managed-instances-cluster --tasks arn:aws:ecs:region:aws_account_id:task/managed-instances-cluster/EXAMPLE
```

 輸出顯示任務正在 Amazon ECS 受管執行個體上執行，並包含容器執行個體 ARN：

```
{
    "tasks": [
        {
            "launchType": "MANAGED_INSTANCES",
            "capacityProviderName": "managed-instances-cp",
            "containerInstanceArn": "arn:aws:ecs:region:aws_account_id:container-instance/managed-instances-cluster/CONTAINER_INSTANCE_ID",
            "taskArn": "arn:aws:ecs:region:aws_account_id:task/managed-instances-cluster/EXAMPLE",
            "taskDefinitionArn": "arn:aws:ecs:region:aws_account_id:task-definition/sample-managed-instances:1"
        }
    ]
}
```

 描述容器執行個體以取得 EC2 執行個體 ID：

```
aws ecs describe-container-instances --cluster managed-instances-cluster --container-instances CONTAINER_INSTANCE_ID
```

 輸出包含 EC2 執行個體 ID：

```
{
    "containerInstances": [
        {
            "ec2InstanceId": "i-1234567890abcdef0",
            "capacityProviderName": "managed-instances-cp",
            "containerInstanceArn": "arn:aws:ecs:region:aws_account_id:container-instance/managed-instances-cluster/CONTAINER_INSTANCE_ID"
        }
    ]
}
```

 描述 EC2 執行個體以取得公有 IP 位址：

```
aws ec2 describe-instances --instance-ids i-1234567890abcdef0
```

 輸出中包含公有 IP 位址：

```
{
    "Reservations": [
        {
            "Instances": [
                {
                    "PublicIpAddress": "198.51.100.2",
                    "InstanceId": "i-1234567890abcdef0"
                }
            ]
        }
    ]
}
```

 在 Web 瀏覽器中輸入公有 IP 位址，然後您應該會看到一個網頁，其中顯示正在 Amazon ECS 受管執行個體上執行的 **Amazon ECS** 範例應用程式。

### 使用私有子網路部署的測試任務
<a name="managed-instances-cli-test-private-subnet"></a>

 對於部署在私有子網路中的任務，您可以使用 Amazon ECS Exec 連線至容器，並從執行個體內測試部署。請遵循上述相同步驟取得任務 ARN，然後使用 ECS Exec：

```
aws ecs execute-command --cluster managed-instances-cluster \
    --task arn:aws:ecs:region:aws_account_id:task/managed-instances-cluster/EXAMPLE \
    --container managed-instances-app \
    --interactive \
    --command "/bin/sh"
```

 在互動式 Shell 執行後，您可以測試該 Web 伺服器：

```
curl localhost
```

 您應該會看到相當於 **Amazon ECS** 範例應用程式網頁的 HTML。

## 步驟 10：清除
<a name="managed-instances-cli-clean-up"></a>

 完成此教學課程時，建議您清除相關聯的資源，以免未使用的資源產生費用。

 刪除服務：

```
aws ecs delete-service --cluster managed-instances-cluster --service managed-instances-service --force
```

 等待刪除服務並停止所有任務，然後刪除容量提供者：

```
aws ecs delete-capacity-provider --capacity-provider managed-instances-cp
```

 刪除 叢集：

```
aws ecs delete-cluster --cluster managed-instances-cluster
```

**注意**  
 容量提供者刪除後，受管執行個體會自動終止。您無需手動終止 EC2 執行個體。