

本文属于机器翻译版本。若本译文内容与英语原文存在差异，则一律以英文原文为准。

# 将应用程序规范文件添加到修订版中 CodeDeploy
<a name="application-revisions-appspec-file"></a>

本主题介绍如何向部署中添加 AppSpec 文件。它还包括用于为 AWS Lambda 和 EC2/本地部署创建 AppSpec 文件的模板。

**Topics**
+ [为 Amazon ECS 部署添加 AppSpec 文件](#add-appspec-file-ecs)
+ [为 AWS Lambda 部署添加 AppSpec 文件](#add-appspec-file-lambda)
+ [为 EC2/本地部署添加 AppSpec 文件](#add-appspec-file-server)

## 为 Amazon ECS 部署添加 AppSpec 文件
<a name="add-appspec-file-ecs"></a>

对于向 Amazon ECS 计算平台进行的部署：
+ 该 AppSpec 文件指定了用于部署的 Amazon ECS 任务定义、用于路由流量的容器名称和端口映射，以及部署生命周期事件之后运行的可选 Lambda 函数。
+ 修订版与 AppSpec 文件相同。
+ 可以使用 JSON 或 YAML 写入 AppSpec 文件。
+ 创建部署时，可以将文件另存为文本文件或直接输入到控制台中。 AppSpec 有关更多信息，请参阅 [创建 Amazon ECS 计算平台部署（控制台）](deployments-create-console-ecs.md)。

**创建 AppSpec 文件**

1. 将 JSON 或 YAML 模板复制到文本编辑器或控制台的 AppSpec 编辑器中。

1. 根据需要修改模板。

1. 使用 JSON 或 YAML 验证器来验证您的文件。 AppSpec 如果您使用 AppSpec编辑器，则在选择 “**创建部署**” 时会对文件进行验证。

1. 如果您使用文本编辑器，请保存该文件。如果您使用创建部署， AWS CLI 请引用该文件（如果该 AppSpec 文件位于您的硬盘或 Amazon S3 存储桶中）。如果您使用控制台，则必须将 AppSpec 文件推送到 Amazon S3。

### 带说明的 Amazon ECS 部署的 YAML AppSpec 文件模板
<a name="app-spec-template-yaml-ecs"></a>

以下是 Amazon ECS 部署 AppSpec 文件的 YAML 模板，其中包含所有可用选项。有关在 `hooks` 部分中使用的生命周期事件的信息，请参阅[AppSpec 亚马逊 ECS 部署的 “挂钩” 部分](reference-appspec-file-structure-hooks.md#appspec-hooks-ecs)。

```
# This is an appspec.yml template file for use with an Amazon ECS deployment in CodeDeploy.
# The lines in this template that start with the hashtag are 
#   comments that can be safely left in the file or 
#   ignored.
# For help completing this file, see the "AppSpec File Reference" in the  
#   "CodeDeploy User Guide" at
#   https://docs.aws.amazon.com/codedeploy/latest/userguide/app-spec-ref.html
version: 0.0
# In the Resources section, you must specify the following: the Amazon ECS service, task definition name, 
# and the name and port of the load balancer to route traffic,
# target version, and (optional) the current version of your AWS Lambda function. 
Resources:
  - TargetService:
      Type: AWS::ECS::Service
      Properties:
        TaskDefinition: "" # Specify the ARN of your task definition (arn:aws:ecs:region:account-id:task-definition/task-definition-family-name:task-definition-revision-number)
        LoadBalancerInfo: 
          ContainerName: "" # Specify the name of your Amazon ECS application's container
          ContainerPort: "" # Specify the port for your container where traffic reroutes 
# Optional properties
        PlatformVersion: "" # Specify the version of your Amazon ECS Service
        NetworkConfiguration:
          AwsvpcConfiguration:
            Subnets: ["",""] # Specify one or more comma-separated subnets in your Amazon ECS service
            SecurityGroups: ["",""] # Specify one or more comma-separated security groups in your Amazon ECS service
            AssignPublicIp: "" # Specify "ENABLED" or "DISABLED"             
# (Optional) In the Hooks section, specify a validation Lambda function to run during 
# a lifecycle event. 
Hooks:
# Hooks for Amazon ECS deployments are:
    - BeforeInstall: "" # Specify a Lambda function name or ARN
    - AfterInstall: "" # Specify a Lambda function name or ARN
    - AfterAllowTestTraffic: "" # Specify a Lambda function name or ARN
    - BeforeAllowTraffic: "" # Specify a Lambda function name or ARN
    - AfterAllowTraffic: "" # Specify a Lambda function name or ARN
```

### 亚马逊 ECS 部署模板的 JSON AppSpec 文件
<a name="app-spec-template-json-ecs"></a>

以下是 Amazon ECS 部署 AppSpec 文件的 JSON 模板，其中包含所有可用选项。有关模板说明，请参阅上一部分中 YAML 版本中的注释。有关在 `hooks` 部分中使用的生命周期事件的信息，请参阅[AppSpec 亚马逊 ECS 部署的 “挂钩” 部分](reference-appspec-file-structure-hooks.md#appspec-hooks-ecs)。

```
{
	"version": 0.0,
	"Resources": [
		{
			"TargetService": {
				"Type": "AWS::ECS::Service",
				"Properties": {
    			"TaskDefinition": "",
    			"LoadBalancerInfo": {
    				"ContainerName": "",
    				"ContainerPort":
    			},
    			"PlatformVersion": "",
    			"NetworkConfiguration": {
    				"AwsvpcConfiguration": {
    					"Subnets": [
    						"",
    						""
    					],
    					"SecurityGroups": [
    						"",
    						""
    					],
    					"AssignPublicIp": ""
    				}
    			}
  			}				
			}
		}
	],
	"Hooks": [
		{
			"BeforeInstall": ""
		},
		{
			"AfterInstall": ""
		},
		{
			"AfterAllowTestTraffic": ""
		},
		{
			"BeforeAllowTraffic": ""
		},
		{
			"AfterAllowTraffic": ""
		}
	]
}
```

## 为 AWS Lambda 部署添加 AppSpec 文件
<a name="add-appspec-file-lambda"></a>

要部署到 AWS Lambda 计算平台，请执行以下操作：
+ 该 AppSpec 文件包含有关要部署和用于部署验证的 Lambda 函数的说明。
+ 修订版与 AppSpec 文件相同。
+ 可以使用 JSON 或 YAML 写入 AppSpec 文件。
+ 创建部署时，可以将文件另存为文本文件或直接输入到控制台 AppSpec 编辑器中。 AppSpec 有关更多信息，请参阅 [创建 L AWS ambda 计算平台部署（控制台）](deployments-create-console-lambda.md)。

要创建 AppSpec 文件，请执行以下操作：

1. 将 JSON 或 YAML 模板复制到文本编辑器或控制台的 AppSpec 编辑器中。

1. 根据需要修改模板。

1. 使用 JSON 或 YAML 验证器来验证您的文件。 AppSpec 如果您使用 AppSpec编辑器，则在选择 “**创建部署**” 时会对文件进行验证。

1. 如果您使用文本编辑器，请保存该文件。如果您使用创建部署， AWS CLI 请引用该文件（如果该 AppSpec 文件位于您的硬盘或 Amazon S3 存储桶中）。如果您使用控制台，则必须将 AppSpec 文件推送到 Amazon S3。



### 带有说明的 AWS Lambda 部署的 YAML AppSpec 文件模板
<a name="app-spec-template-yaml-lambda"></a>

有关在 hooks 部分中使用的生命周期事件的信息，请参阅[AppSpec AWS Lambda 部署的 “挂钩” 部分](reference-appspec-file-structure-hooks.md#appspec-hooks-lambda)。

```
# This is an appspec.yml template file for use with an AWS Lambda deployment in CodeDeploy.
# The lines in this template starting with the hashtag symbol are 
#   instructional comments and can be safely left in the file or 
#   ignored.
# For help completing this file, see the "AppSpec File Reference" in the  
#   "CodeDeploy User Guide" at
#   https://docs.aws.amazon.com/codedeploy/latest/userguide/app-spec-ref.html
version: 0.0
# In the Resources section specify the name, alias, 
# target version, and (optional) the current version of your AWS Lambda function. 
Resources:
  - MyFunction: # Replace "MyFunction" with the name of your Lambda function 
      Type: AWS::Lambda::Function
      Properties:
        Name: "" # Specify the name of your Lambda function
        Alias: "" # Specify the alias for your Lambda function
        CurrentVersion: "" # Specify the current version of your Lambda function
        TargetVersion: "" # Specify the version of your Lambda function to deploy
# (Optional) In the Hooks section, specify a validation Lambda function to run during 
# a lifecycle event. Replace "LifeCycleEvent" with BeforeAllowTraffic
# or AfterAllowTraffic. 
Hooks:
    - LifeCycleEvent: "" # Specify a Lambda validation function between double-quotes.
```

### AWS Lambda 部署模板 AppSpec 的 JSON 文件
<a name="app-spec-template-json-lambda"></a>

在以下模板中，将 “MyFunction” 替换为您的 AWS Lambda 函数名称。在可选的 Hooks 部分中，将生命周期事件替换为 BeforeAllowTraffic 或 AfterAllowTraffic。

有关在 Hooks 部分中使用的生命周期事件的信息，请参阅[AppSpec AWS Lambda 部署的 “挂钩” 部分](reference-appspec-file-structure-hooks.md#appspec-hooks-lambda)。

```
{
 	"version": 0.0,
 	"Resources": [{
 		"MyFunction": {
 			"Type": "AWS::Lambda::Function",
 			"Properties": {
 				"Name": "",
 				"Alias": "",
 				"CurrentVersion": "",
 				"TargetVersion": ""
 			}
 		}
 	}],
 	"Hooks": [{
 			"LifeCycleEvent": ""
 		}
 	]
 }
```

## 为 EC2/本地部署添加 AppSpec 文件
<a name="add-appspec-file-server"></a>

如果没有 AppSpec 文件， CodeDeploy 则无法将应用程序修订版中的源文件映射到其目的地，也无法运行脚本以部署到 EC2/本地计算平台。

每个修订版只能包含一个 AppSpec 文件。

要向修订版中添加 AppSpec 文件，请执行以下操作：

1. 将模板复制到文本编辑器。

1. 根据需要修改模板。

1. 使用 YAML 验证器检查文件的有效性。 AppSpec 

1. 在修订的根目录中将文件另存为 `appspec.yml`。

1. 运行以下命令之一，验证是否已将 AppSpec 文件放在根目录中：
   + 对于 Linux、macOS 或 Unix：

     ```
     find /path/to/root/directory -name appspec.yml
     ```

     如果在那里找不到 AppSpec 文件，则不会有输出。
   + 对于 Windows：

     ```
     dir path\to\root\directory\appspec.yml
     ```

     如果**文件未存储在那里，则会显示 “找**不到 AppSpec 文件” 错误。

1. 将修订版推送到 Amazon S3 或 GitHub。

   有关说明，请参阅[将修订推送 CodeDeploy 到 Amazon S3（仅限 EC2/本地部署）](application-revisions-push.md)。

### AppSpec 带说明的 EC2/本地部署的文件模板
<a name="app-spec-template-server"></a>

**注意**  
 部署到 Windows Server 实例不支持 `runas` 元素。如果您要部署到 Windows 服务器实例，请不要将其包含在 AppSpec 文件中。

```
# This is an appspec.yml template file for use with an EC2/On-Premises deployment in CodeDeploy.
# The lines in this template starting with the hashtag symbol are 
#   instructional comments and can be safely left in the file or 
#   ignored.
# For help completing this file, see the "AppSpec File Reference" in the  
#   "CodeDeploy User Guide" at
#   https://docs.aws.amazon.com/codedeploy/latest/userguide/app-spec-ref.html
version: 0.0
# Specify "os: linux" if this revision targets Amazon Linux, 
#   Red Hat Enterprise Linux (RHEL), or Ubuntu Server  
#   instances.
# Specify "os: windows" if this revision targets Windows Server instances.
# (You cannot specify both "os: linux" and "os: windows".)
os: linux 
# os: windows
# During the Install deployment lifecycle event (which occurs between the 
#   BeforeInstall and AfterInstall events), copy the specified files 
#   in "source" starting from the root of the revision's file bundle 
#   to "destination" on the Amazon EC2 instance.
# Specify multiple "source" and "destination" pairs if you want to copy 
#   from multiple sources or to multiple destinations.
# If you are not copying any files to the Amazon EC2 instance, then remove the
#   "files" section altogether. A blank or incomplete "files" section
#   may cause associated deployments to fail.
files:
  - source: 
    destination:
  - source:
    destination:
# For deployments to Amazon Linux, Ubuntu Server, or RHEL instances,
#   you can specify a "permissions" 
#   section here that describes special permissions to apply to the files 
#   in the "files" section as they are being copied over to 
#   the Amazon EC2 instance.
#   For more information, see the documentation.
# If you are deploying to Windows Server instances,
#   then remove the 
#   "permissions" section altogether. A blank or incomplete "permissions"
#   section may cause associated deployments to fail.
permissions:
  - object:
    pattern:
    except:
    owner:
    group:
    mode: 
    acls:
      -
    context:
      user:
      type:
      range:
    type:
      -
# If you are not running any commands on the Amazon EC2 instance, then remove 
#   the "hooks" section altogether. A blank or incomplete "hooks" section
#   may cause associated deployments to fail.
hooks:
# For each deployment lifecycle event, specify multiple "location" entries 
#   if you want to run multiple scripts during that event.
# You can specify "timeout" as the number of seconds to wait until failing the deployment 
#   if the specified scripts do not run within the specified time limit for the 
#   specified event. For example, 900 seconds is 15 minutes. If not specified, 
#   the default is 1800 seconds (30 minutes).
#   Note that the maximum amount of time that all scripts must finish executing 
#   for each individual deployment lifecycle event is 3600 seconds (1 hour). 
#   Otherwise, the deployment will stop and CodeDeploy will consider the deployment
#   to have failed to the Amazon EC2 instance. Make sure that the total number of seconds 
#   that are specified in "timeout" for all scripts in each individual deployment 
#   lifecycle event does not exceed a combined 3600 seconds (1 hour).
# For deployments to Amazon Linux, Ubuntu Server, or RHEL instances,
#   you can specify "runas" in an event to
#   run as the specified user. For more information, see the documentation.
#   If you are deploying to Windows Server instances,
#   remove "runas" altogether.
# If you do not want to run any commands during a particular deployment
#   lifecycle event, remove that event declaration altogether. Blank or 
#   incomplete event declarations may cause associated deployments to fail.
# During the ApplicationStop deployment lifecycle event, run the commands 
#   in the script specified in "location" starting from the root of the 
#   revision's file bundle.
  ApplicationStop:
    - location: 
      timeout:
      runas:
    - location: 
      timeout:
      runas: 
# During the BeforeInstall deployment lifecycle event, run the commands 
#   in the script specified in "location".
  BeforeInstall:
    - location: 
      timeout:
      runas: 
    - location: 
      timeout:
      runas:
# During the AfterInstall deployment lifecycle event, run the commands 
#   in the script specified in "location".
  AfterInstall:
    - location:     
      timeout: 
      runas:
    - location: 
      timeout:
      runas:
# During the ApplicationStart deployment lifecycle event, run the commands 
#   in the script specified in "location".
  ApplicationStart:
    - location:     
      timeout: 
      runas:
    - location: 
      timeout:
      runas:
# During the ValidateService deployment lifecycle event, run the commands 
#   in the script specified in "location".
  ValidateService:
    - location:     
      timeout: 
      runas:
    - location: 
      timeout:
      runas:
```