

# 教程：使用蓝/绿部署创建服务
<a name="create-blue-green"></a>

Amazon ECS 已将蓝/绿部署集成到 Amazon ECS 控制台的创建服务向导中。有关更多信息，请参阅 [创建 Amazon ECS 滚动更新部署](create-service-console-v2.md)。

以下教程说明如何创建一个 Amazon ECS 服务，该服务包含一个将蓝/绿部署类型与 AWS CLI 结合使用的 Fargate 任务。

**注意**  
为 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 和安全组。有关更多信息，请参阅 [创建虚拟私有云](get-set-up-for-amazon-ecs.md#create-a-vpc)。
+ 创建 Amazon ECS CodeDeploy IAM 角色。有关更多信息，请参阅 [Amazon ECS CodeDeploy IAM 角色](codedeploy_IAM_role.md)。

## 步骤 1：创建应用程序负载均衡器
<a name="create-blue-green-loadbalancer"></a>

使用蓝绿部署类型的 Amazon ECS 服务需要使用应用程序负载均衡器或网络负载均衡器。本教程使用应用程序负载均衡器。

**创建应用程序负载均衡器**

1. 使用 [create-load-balancer](https://docs.aws.amazon.com/cli/latest/reference/elbv2/create-load-balancer.html) 命令创建应用程序负载均衡器。指定两个不属于同一可用区的子网以及一个安全组。

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

   输出包含负载均衡器的 Amazon 资源名称（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 部署组的应用程序负载均衡器目标组以及 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) 命令创建另一个应用程序负载均衡器目标组（在创建 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. 使用 CodeDeploy 部署组的内容创建名为 `appspec.yaml` 的文件。此示例使用您在本教程前面创建的资源。

      ```
      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. 使用 CodeDeploy 部署的内容创建名为 `create-deployment.json` 的文件。此示例使用您在本教程前面创建的资源。

      ```
      {
          "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` 标记，您可以删除服务，即使它尚未缩减至 0 个任务。

   ```
   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) 命令从 Amazon S3 存储桶中删除 AppSpec 文件。

   ```
   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) 命令删除应用程序负载均衡器。

   ```
   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) 命令删除两个应用程序负载均衡器目标组。

   ```
   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
   ```