

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

# 教學課程：使用藍/綠部署建立服務
<a name="create-blue-green"></a>

Amazon ECS 已將藍/綠部署整合至 Amazon ECS 主控台內的建立服務精靈。如需詳細資訊，請參閱[建立 Amazon ECS 滾動更新部署](create-service-console-v2.md)。

以下教學課程說明如何在 AWS CLI透過使用藍/綠部署類型的 Fargate 任務建立 Amazon ECS 服務。

**注意**  
已為 CloudFormation新增對於執行藍/綠部署的支援。如需詳細資訊，請參閱 *AWS CloudFormation 使用者指南*中的[使用 CloudFormation透過 CodeDeploy 執行 Amazon ECS 藍/綠部署](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/blue-green.html)。

## 先決條件
<a name="create-blue-green-prereqs"></a>

本教學課程假設已完成下列先決條件：
+  AWS CLI 已安裝並設定最新版本的 。如需安裝或升級 的詳細資訊 AWS CLI，請參閱[安裝 AWS Command Line Interface](https://docs.aws.amazon.com/cli/latest/userguide/installing.html)。
+ 已完成「[設定以使用 Amazon ECS。](get-set-up-for-amazon-ecs.md)」中的步驟。
+ 您的 IAM 使用者擁有 [AmazonECS\$1FullAccess](security-iam-awsmanpol.md#security-iam-awsmanpol-AmazonECS_FullAccess) IAM 政策範例中指定的所需許可。
+ 您已建立 VPC 和安全群組。如需詳細資訊，請參閱[建立 Virtual Private Cloud](get-set-up-for-amazon-ecs.md#create-a-vpc)。
+ 已建立 Amazon ECS CodeDeploy IAM 角色。如需詳細資訊，請參閱[Amazon ECS CodeDeploy IAM 角色](codedeploy_IAM_role.md)。

## 步驟 1：建立 Application Load Balancer
<a name="create-blue-green-loadbalancer"></a>

使用藍/綠部署類型的 Amazon ECS 服務需要使用 Application Load Balancer 或 Network Load Balancer。本教學課程會使用 Application Load Balancer。

**建立 Application Load Balancer**

1. 使用 [create-load-balancer](https://docs.aws.amazon.com/cli/latest/reference/elbv2/create-load-balancer.html) 命令來建立 Application Load Balancer。指定並非來自與安全群組相同可用區域的兩個子網路。

   ```
   aws elbv2 create-load-balancer \
        --name bluegreen-alb \
        --subnets subnet-abcd1234 subnet-abcd5678 \
        --security-groups sg-abcd1234 \
        --region us-east-1
   ```

   其輸出將包含負載平衡器的 Amazon Resource Name (ARN)，格式如下：

   ```
   arn:aws:elasticloadbalancing:region:aws_account_id:loadbalancer/app/bluegreen-alb/e5ba62739c16e642
   ```

1. 使用 [create-target-group](https://docs.aws.amazon.com/cli/latest/reference/elbv2/create-target-group.html) 命令建立目標群組。此目標群組會將流量路由到服務中的原始任務集。

   ```
   aws elbv2 create-target-group \
        --name bluegreentarget1 \
        --protocol HTTP \
        --port 80 \
        --target-type ip \
        --vpc-id vpc-abcd1234 \
        --region us-east-1
   ```

   其輸出將包含目標群組的 ARN，格式如下：

   ```
   arn:aws:elasticloadbalancing:region:aws_account_id:targetgroup/bluegreentarget1/209a844cd01825a4
   ```

1. 使用 [create-listener](https://docs.aws.amazon.com/cli/latest/reference/elbv2/create-listener.html) 命令建立具有預設規則以將請求轉送至目標群組的負載平衡接聽程式。

   ```
   aws elbv2 create-listener \
        --load-balancer-arn arn:aws:elasticloadbalancing:region:aws_account_id:loadbalancer/app/bluegreen-alb/e5ba62739c16e642 \
        --protocol HTTP \
        --port 80 \
        --default-actions Type=forward,TargetGroupArn=arn:aws:elasticloadbalancing:region:aws_account_id:targetgroup/bluegreentarget1/209a844cd01825a4 \
        --region us-east-1
   ```

   其輸出將包含接聽程式的 ARN，格式如下：

   ```
   arn:aws:elasticloadbalancing:region:aws_account_id:listener/app/bluegreen-alb/e5ba62739c16e642/665750bec1b03bd4
   ```

## 步驟 2：建立 Amazon ECS 叢集
<a name="create-blue-green-cluster"></a>

使用 [create-cluster](https://docs.aws.amazon.com/cli/latest/reference/ecs/create-cluster.html) 命令來建立要使用之名為 `tutorial-bluegreen-cluster` 的叢集。

```
aws ecs create-cluster \
     --cluster-name tutorial-bluegreen-cluster \
     --region us-east-1
```

其輸出將包含叢集的 ARN，格式如下：

```
arn:aws:ecs:region:aws_account_id:cluster/tutorial-bluegreen-cluster
```

## 步驟 3：註冊任務定義
<a name="create-blue-green-taskdef"></a>

使用 [register-task-definition](https://docs.aws.amazon.com/cli/latest/reference/ecs/register-task-definition.html) 命令來註冊與 Fargate 相容的任務定義。這需要使用 `awsvpc` 網路模式。以下是用於此教學課程的任務定義範例。

首先，建立名為 `fargate-task.json` 且具有下列內容的檔案。確保您使用的是任務執行角色的 ARN。如需詳細資訊，請參閱[Amazon ECS 任務執行 IAM 角色](task_execution_IAM_role.md)。

```
{
    "family": "sample-fargate", 
    "networkMode": "awsvpc", 
    "containerDefinitions": [
        {
            "name": "sample-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.</p> </div></body></html>' >  /usr/local/apache2/htdocs/index.html && httpd-foreground\""
            ]
        }
    ], 
    "requiresCompatibilities": [
        "FARGATE"
    ], 
    "cpu": "256", 
    "memory": "512"
}
```

接下來，使用您建立的 `fargate-task.json` 檔案註冊任務定義。

```
aws ecs register-task-definition \
     --cli-input-json file://fargate-task.json \
     --region us-east-1
```

## 步驟 4：建立 Amazon ECS 服務
<a name="create-blue-green-service"></a>

使用 [create-service](https://docs.aws.amazon.com/cli/latest/reference/ecs/create-service.html) 命令來建立服務。

首先，建立名為 `service-bluegreen.json` 且具有下列內容的檔案。

```
{
    "cluster": "tutorial-bluegreen-cluster",
    "serviceName": "service-bluegreen",
    "taskDefinition": "tutorial-task-def",
    "loadBalancers": [
        {
            "targetGroupArn": "arn:aws:elasticloadbalancing:region:aws_account_id:targetgroup/bluegreentarget1/209a844cd01825a4",
            "containerName": "sample-app",
            "containerPort": 80
        }
    ],
    "launchType": "FARGATE",
    "schedulingStrategy": "REPLICA",
    "deploymentController": {
        "type": "CODE_DEPLOY"
    },
    "platformVersion": "LATEST",
    "networkConfiguration": {
       "awsvpcConfiguration": {
          "assignPublicIp": "ENABLED",
          "securityGroups": [ "sg-abcd1234" ],
          "subnets": [ "subnet-abcd1234", "subnet-abcd5678" ]
       }
    },
    "desiredCount": 1
}
```

接下來，使用您建立的 `service-bluegreen.json` 檔案建立服務。

```
aws ecs create-service \
     --cli-input-json file://service-bluegreen.json \
     --region us-east-1
```

其輸出將包含服務的 ARN，格式如下：

```
arn:aws:ecs:region:aws_account_id:service/service-bluegreen
```

## 步驟 5：建立 AWS CodeDeploy 資源
<a name="create-blue-green-codedeploy"></a>

請依照下列步驟建立 CodeDeploy 應用程式、CodeDeploy 部署群組的 Application Load Balancer 目標群組，以及 CodeDeploy 部署群組。

**建立 CodeDeploy 資源**

1. 使用 [create-application](https://docs.aws.amazon.com/cli/latest/reference/deploy/create-application.html) 命令建立 CodeDeploy 應用程式。指定 `ECS` 運算平台。

   ```
   aws deploy create-application \
        --application-name tutorial-bluegreen-app \
        --compute-platform ECS \
        --region us-east-1
   ```

   其輸出將包含應用程式 ID，格式如下：

   ```
   {
       "applicationId": "b8e9c1ef-3048-424e-9174-885d7dc9dc11"
   }
   ```

1. 使用 [create-target-group](https://docs.aws.amazon.com/cli/latest/reference/elbv2/create-target-group.html) 命令建立第二個 Application Load Balancer 目標群組，該群組會在您建立 CodeDeploy 部署群組時用到。

   ```
   aws elbv2 create-target-group \
        --name bluegreentarget2 \
        --protocol HTTP \
        --port 80 \
        --target-type ip \
        --vpc-id "vpc-0b6dd82c67d8012a1" \
        --region us-east-1
   ```

   其輸出將包含目標群組的 ARN，格式如下：

   ```
   arn:aws:elasticloadbalancing:region:aws_account_id:targetgroup/bluegreentarget2/708d384187a3cfdc
   ```

1. 使用 [create-deployment-group](https://docs.aws.amazon.com/cli/latest/reference/deploy/create-deployment-group.html) 命令建立 CodeDeploy 部署群組。

   首先，建立名為 `tutorial-deployment-group.json` 且具有下列內容的檔案。此範例會使用您建立的資源。對於 `serviceRoleArn`，請指定 Amazon ECS CodeDeploy IAM 角色的 ARN。如需詳細資訊，請參閱[Amazon ECS CodeDeploy IAM 角色](codedeploy_IAM_role.md)。

   ```
   {
      "applicationName": "tutorial-bluegreen-app",
      "autoRollbackConfiguration": {
         "enabled": true,
         "events": [ "DEPLOYMENT_FAILURE" ]
      },
      "blueGreenDeploymentConfiguration": {
         "deploymentReadyOption": {
            "actionOnTimeout": "CONTINUE_DEPLOYMENT",
            "waitTimeInMinutes": 0
         },
         "terminateBlueInstancesOnDeploymentSuccess": {
            "action": "TERMINATE",
            "terminationWaitTimeInMinutes": 5
         }
      },
      "deploymentGroupName": "tutorial-bluegreen-dg",
      "deploymentStyle": {
         "deploymentOption": "WITH_TRAFFIC_CONTROL",
         "deploymentType": "BLUE_GREEN"
      },
      "loadBalancerInfo": {
         "targetGroupPairInfoList": [
           {
             "targetGroups": [
                {
                    "name": "bluegreentarget1"
                },
                {
                    "name": "bluegreentarget2"
                }
             ],
             "prodTrafficRoute": {
                 "listenerArns": [
                     "arn:aws:elasticloadbalancing:region:aws_account_id:listener/app/bluegreen-alb/e5ba62739c16e642/665750bec1b03bd4"
                 ]
             }
           }
         ]
      },
      "serviceRoleArn": "arn:aws:iam::aws_account_id:role/ecsCodeDeployRole",
      "ecsServices": [
          {
              "serviceName": "service-bluegreen",
              "clusterName": "tutorial-bluegreen-cluster"
          }
      ]
   }
   ```

   接著建立 CodeDeploy 部署群組。

   ```
   aws deploy create-deployment-group \
        --cli-input-json file://tutorial-deployment-group.json \
        --region us-east-1
   ```

   其輸出將包含部署群組 ID，格式如下：

   ```
   {
       "deploymentGroupId": "6fd9bdc6-dc51-4af5-ba5a-0a4a72431c88"
   }
   ```

## 步驟 6：建立與監控 CodeDeploy 部署
<a name="create-blue-green-verify"></a>

使用以下步驟來建立和上傳應用程式規格檔案 (AppSpec 檔案) 和 CodeDeploy 部署。

**建立和監控 CodeDeploy 部署**

1. 使用以下步驟來建立和上傳 AppSpec 檔案。

   1. 建立名為 `appspec.yaml` 並具有 CodeDeploy 部署群組內容的檔案。此範例會使用您先前在教學課程中建立的資源。

      ```
      version: 0.0
      Resources:
        - TargetService:
            Type: AWS::ECS::Service
            Properties:
              TaskDefinition: "arn:aws:ecs:region:aws_account_id:task-definition/first-run-task-definition:7"
              LoadBalancerInfo:
                ContainerName: "sample-app"
                ContainerPort: 80
              PlatformVersion: "LATEST"
      ```

   1. 使用 [s3 mb](https://docs.aws.amazon.com/cli/latest/reference/s3/mb.html) 命令為 AppSpec 檔案建立 Amazon S3 儲存貯體。

      ```
      aws s3 mb s3://tutorial-bluegreen-bucket
      ```

   1. 使用 [s3 cp](https://docs.aws.amazon.com/cli/latest/reference/s3/cp.html) 命令來將 AppSpec 檔案上傳至 Amazon S3 儲存貯體。

      ```
      aws s3 cp ./appspec.yaml s3://tutorial-bluegreen-bucket/appspec.yaml
      ```

1. 使用下列步驟來建立 CodeDeploy 部署。

   1. 建立名為 `create-deployment.json` 並具有 CodeDeploy 部署內容的檔案。此範例會使用您先前在教學課程中建立的資源。

      ```
      {
          "applicationName": "tutorial-bluegreen-app",
          "deploymentGroupName": "tutorial-bluegreen-dg",
          "revision": {
              "revisionType": "S3",
              "s3Location": {
                  "bucket": "tutorial-bluegreen-bucket",
                  "key": "appspec.yaml",
                  "bundleType": "YAML"
              }
          }
      }
      ```

   1. 使用 [create-deployment](https://docs.aws.amazon.com/cli/latest/reference/deploy/create-deployment.html) 命令來建立部署。

      ```
      aws deploy create-deployment \
           --cli-input-json file://create-deployment.json \
           --region us-east-1
      ```

      其輸出將包含部署 ID，格式如下：

      ```
      {
          "deploymentId": "d-RPCR1U3TW"
      }
      ```

   1. 使用 [get-deployment-target](https://docs.aws.amazon.com/cli/latest/reference/deploy/get-deployment-target.html) 命令，並從先前的輸出中指定 `deploymentId` 來取得部署的詳細資訊。

      ```
      aws deploy get-deployment-target \
           --deployment-id "d-IMJU3A8TW" \
           --target-id tutorial-bluegreen-cluster:service-bluegreen \
           --region us-east-1
      ```

      繼續擷取狀態變為 `Succeeded` 前的部署詳細資訊，如下列輸出所示。

      ```
      {
          "deploymentTarget": {
              "deploymentTargetType": "ECSTarget",
              "ecsTarget": {
                  "deploymentId": "d-RPCR1U3TW",
                  "targetId": "tutorial-bluegreen-cluster:service-bluegreen",
                  "targetArn": "arn:aws:ecs:region:aws_account_id:service/service-bluegreen",
                  "lastUpdatedAt": 1543431490.226,
                  "lifecycleEvents": [
                      {
                          "lifecycleEventName": "BeforeInstall",
                          "startTime": 1543431361.022,
                          "endTime": 1543431361.433,
                          "status": "Succeeded"
                      },
                      {
                          "lifecycleEventName": "Install",
                          "startTime": 1543431361.678,
                          "endTime": 1543431485.275,
                          "status": "Succeeded"
                      },
                      {
                          "lifecycleEventName": "AfterInstall",
                          "startTime": 1543431485.52,
                          "endTime": 1543431486.033,
                          "status": "Succeeded"
                      },
                      {
                          "lifecycleEventName": "BeforeAllowTraffic",
                          "startTime": 1543431486.838,
                          "endTime": 1543431487.483,
                          "status": "Succeeded"
                      },
                      {
                          "lifecycleEventName": "AllowTraffic",
                          "startTime": 1543431487.748,
                          "endTime": 1543431488.488,
                          "status": "Succeeded"
                      },
                      {
                          "lifecycleEventName": "AfterAllowTraffic",
                          "startTime": 1543431489.152,
                          "endTime": 1543431489.885,
                          "status": "Succeeded"
                      }
                  ],
                  "status": "Succeeded",
                  "taskSetsInfo": [
                      {
                          "identifer": "ecs-svc/9223370493425779968",
                          "desiredCount": 1,
                          "pendingCount": 0,
                          "runningCount": 1,
                          "status": "ACTIVE",
                          "trafficWeight": 0.0,
                          "targetGroup": {
                              "name": "bluegreentarget1"
                          }
                      },
                      {
                          "identifer": "ecs-svc/9223370493423413672",
                          "desiredCount": 1,
                          "pendingCount": 0,
                          "runningCount": 1,
                          "status": "PRIMARY",
                          "trafficWeight": 100.0,
                          "targetGroup": {
                              "name": "bluegreentarget2"
                          }
                      }
                  ]
              }
          }
      }
      ```

## 步驟 7：清除
<a name="create-blue-green-cleanup"></a>

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

**清除教學課程資源**

1. 使用 [delete-deployment-group](https://docs.aws.amazon.com/cli/latest/reference/deploy/delete-deployment-group.html) 命令來刪除 CodeDeploy 部署群組。

   ```
   aws deploy delete-deployment-group \
        --application-name tutorial-bluegreen-app \
        --deployment-group-name tutorial-bluegreen-dg \
        --region us-east-1
   ```

1. 使用 [delete-application](https://docs.aws.amazon.com/cli/latest/reference/deploy/delete-application.html) 命令來刪除 CodeDeploy 應用程式。

   ```
   aws deploy delete-application \
        --application-name tutorial-bluegreen-app \
        --region us-east-1
   ```

1. 使用 [delete-service](https://docs.aws.amazon.com/cli/latest/reference/ecs/delete-service.html) 命令來刪除 Amazon ECS 服務。使用 `--force` 旗標可讓您即使在服務未縮減為零個任務時仍能將其刪除。

   ```
   aws ecs delete-service \
        --service arn:aws:ecs:region:aws_account_id:service/service-bluegreen \
        --force \
        --region us-east-1
   ```

1. 使用 [delete-cluster](https://docs.aws.amazon.com/cli/latest/reference/ecs/delete-cluster.html) 命令來刪除 Amazon ECS 叢集。

   ```
   aws ecs delete-cluster \
        --cluster tutorial-bluegreen-cluster \
        --region us-east-1
   ```

1. 使用 [s3 rm](https://docs.aws.amazon.com/cli/latest/reference/s3/rm.html) 命令來將 AppSpec 檔案從 Amazon S3 儲存貯體中刪除。

   ```
   aws s3 rm s3://tutorial-bluegreen-bucket/appspec.yaml
   ```

1. 使用 [s3 rb](https://docs.aws.amazon.com/cli/latest/reference/s3/rb.html) 命令來刪除 Amazon S3 儲存貯體。

   ```
   aws s3 rb s3://tutorial-bluegreen-bucket
   ```

1. 使用 [delete-load-balancer](https://docs.aws.amazon.com/cli/latest/reference/elbv2/delete-load-balancer.html) 命令刪除 Application Load Balancer。

   ```
   aws elbv2 delete-load-balancer \
        --load-balancer-arn arn:aws:elasticloadbalancing:region:aws_account_id:loadbalancer/app/bluegreen-alb/e5ba62739c16e642 \
        --region us-east-1
   ```

1. 使用 [delete-target-group](https://docs.aws.amazon.com/cli/latest/reference/elbv2/delete-target-group.html) 命令，刪除兩個 Application Load Balancer 目標群組。

   ```
   aws elbv2 delete-target-group \
        --target-group-arn arn:aws:elasticloadbalancing:region:aws_account_id:targetgroup/bluegreentarget1/209a844cd01825a4 \
        --region us-east-1
   ```

   ```
   aws elbv2 delete-target-group \
        --target-group-arn arn:aws:elasticloadbalancing:region:aws_account_id:targetgroup/bluegreentarget2/708d384187a3cfdc \
        --region us-east-1
   ```