

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

# AppSpec 檔案結構
<a name="reference-appspec-file-structure"></a>

以下是 AppSpec 檔案的高階結構，用於部署至 AWS Lambda 和 EC2/現場部署運算平台。

除非另有指定，否則 YAML 格式 AppSpec 檔案中的值若為字串，則不得以引號 ("") 包裝。

## Amazon ECS 部署的 AppSpec 檔案結構
<a name="ecs-appspec-structure"></a>

**注意**  
此 AppSpec 檔案是以 YAML 撰寫，但您可以使用相同的結構在 JSON 中撰寫。JSON 格式 AppSpec 檔案中的字串一律以引號 ("") 包裝。

```
version: 0.0
resources: 
  ecs-service-specifications
hooks: 
  deployment-lifecycle-event-mappings
```

在此結構中：

** **version** **  
本節指定 AppSpec 檔案的版本。請不要變更此值。這是必要項目。目前，唯一允許的值為 **0.0**。它由 CodeDeploy 保留以供日後使用。  
以字串指定 **version**。

** **resources** **  
本節指定要部署之 Amazon ECS 應用程式的相關資訊。  
如需詳細資訊，請參閱[Amazon ECS 部署的 AppSpec 'resources' 區段](reference-appspec-file-structure-resources.md#reference-appspec-file-structure-resources-ecs)。

** **hooks** **  
本節指定要在特定部署生命週期事件掛鉤上執行的 Lambda 函數，以驗證部署。  
如需詳細資訊，請參閱[Amazon ECS 部署的生命週期事件掛鉤清單](reference-appspec-file-structure-hooks.md#reference-appspec-file-structure-hooks-list-ecs)。

## AWS Lambda 部署的 AppSpec 檔案結構
<a name="lambda-appspec-structure"></a>

**注意**  
此 AppSpec 檔案是以 YAML 撰寫，但您可以使用相同的結構來撰寫 JSON 中 Lambda 部署的 AppSpec 檔案。JSON 格式 AppSpec 檔案中的字串一律以引號 ("") 包裝。

```
version: 0.0
resources: 
  lambda-function-specifications
hooks: 
  deployment-lifecycle-event-mappings
```

在此結構中：

** **version** **  
本節指定 AppSpec 檔案的版本。請不要變更此值。這是必要項目。目前，唯一允許的值為 **0.0**。它由 CodeDeploy 保留以供日後使用。  
以字串指定 **version**。

** **resources** **  
本節指定要部署之 Lambda 函數的相關資訊。  
如需詳細資訊，請參閱[AppSpec 'resources' 區段 （僅限 Amazon ECS 和 AWS Lambda 部署）](reference-appspec-file-structure-resources.md)。

** **hooks** **  
本節指定要在特定部署生命週期事件上執行的 Lambda 函數，以驗證部署。  
如需詳細資訊，請參閱[AppSpec 'hooks' 區段](reference-appspec-file-structure-hooks.md)。

## EC2/現場部署的 AppSpec 檔案結構
<a name="server-appspec-structure"></a>

```
version: 0.0
os: operating-system-name
files:
  source-destination-files-mappings
permissions:
  permissions-specifications
hooks:
  deployment-lifecycle-event-mappings
```

在此結構中：

** **version** **  
本節指定 AppSpec 檔案的版本。請不要變更此值。這是必要項目。目前，唯一允許的值為 **0.0**。它由 CodeDeploy 保留以供日後使用。  
以字串指定 **version**。

** **os** **  
本區段指定您要部署之執行個體的作業系統值。這是必要項目。您可以指定的值如下：  
+ **linux** – 執行個體是 Amazon Linux、Ubuntu Server 或 RHEL 執行個體。
+ **windows** – 執行個體是 Windows Server 執行個體。
以字串指定 **os**。

** **files** **  
本區段指定在部署 **Install** 事件期間應該複製至執行個體的檔案名稱。  
如需詳細資訊，請參閱[AppSpec 'files' 區段 （僅限 EC2/內部部署部署）](reference-appspec-file-structure-files.md)。

** **permissions** **  
本區段指定應該如何將特殊許可 (如果有的話) 套用至 `files` 區段中的檔案，因為它們會複製至執行個體。本節僅適用於 Amazon Linux、Ubuntu Server 和 Red Hat Enterprise Linux (RHEL) 執行個體。  
如需詳細資訊，請參閱 [AppSpec 'permissions' 區段 （僅限 EC2/現場部署）](reference-appspec-file-structure-permissions.md)。

** **hooks** **  
本區段指定要在部署期間於特定部署生命週期事件執行的指令碼。  
如需詳細資訊，請參閱[AppSpec 'hooks' 區段](reference-appspec-file-structure-hooks.md)。

**Topics**
+ [Amazon ECS 部署的 AppSpec 檔案結構](#ecs-appspec-structure)
+ [AWS Lambda 部署的 AppSpec 檔案結構](#lambda-appspec-structure)
+ [EC2/現場部署的 AppSpec 檔案結構](#server-appspec-structure)
+ [AppSpec 'files' 區段 （僅限 EC2/內部部署部署）](reference-appspec-file-structure-files.md)
+ [AppSpec 'resources' 區段 （僅限 Amazon ECS 和 AWS Lambda 部署）](reference-appspec-file-structure-resources.md)
+ [AppSpec 'permissions' 區段 （僅限 EC2/現場部署）](reference-appspec-file-structure-permissions.md)
+ [AppSpec 'hooks' 區段](reference-appspec-file-structure-hooks.md)

# AppSpec 'files' 區段 （僅限 EC2/內部部署部署）
<a name="reference-appspec-file-structure-files"></a>

向 CodeDeploy 提供部署安裝****事件期間應該在執行個體上安裝的應用程式修訂版中哪些檔案的相關資訊。唯有您在部署期間將修訂中的檔案複製至執行個體上的位置時，會需要本區段。

本區段的結構如下：

```
files:
  - source: source-file-location-1
    destination: destination-file-location-1
file_exists_behavior: DISALLOW|OVERWRITE|RETAIN
```

您可以設定多個 `source` 和 `destination` 配對。

`source` 說明識別要從修訂複製至執行個體的檔案或目錄：
+ 如果 `source` 是指檔案，只會將指定的檔案複製至執行個體。
+ 如果 `source` 是指目錄，會將該目錄中的所有檔案都複製至執行個體。
+ 如果 `source`是 Amazon Linux、RHEL 和 Ubuntu Server 執行個體的單斜線 ("/"，或 Windows Server 執行個體的 "\$1")，則修訂中的所有檔案都會複製到執行個體。

在 中使用的路徑`source`與 `appspec.yml` 檔案相對，應該位於修訂的根目錄。如需修訂版檔案結構的詳細資訊，請參閱 [規劃 CodeDeploy 的修訂](application-revisions-plan.md)。

`destination` 說明識別執行個體上應該複製檔案的位置。這必須是完整路徑，例如 `/root/destination/directory`（在 Linux、RHEL 和 Ubuntu 上） 或 `c:\destination\folder`（在 Windows 上）。

`source` 和 `destination` 各以字串指定。

`file_exists_behavior` 指示為選用，並指定 CodeDeploy 如何處理已存在於部署目標位置但不屬於先前成功部署的檔案。此設定可以採用下列任何值：
+ DISALLOW：部署失敗。如果未指定任何選項，這也是預設行為。
+ OVERWRITE：目前部署之應用程式修訂版的檔案版本會取代執行個體上已存在的版本。
+ 保留：執行個體上已存在的 檔案版本會保留並做為新部署的一部分使用。

使用 `file_exists_behavior`設定時，請了解此設定：
+ 只能指定一次，並套用至 下列出的所有檔案和目錄`files:`。
+ 優先於 `--file-exists-behavior` AWS CLI 選項和 `fileExistsBehavior` API 選項 （兩者皆為選用）。

以下是 Amazon Linux、Ubuntu Server 或 RHEL 執行個體的範例`files`區段。

```
files:
  - source: Config/config.txt
    destination: /webapps/Config
  - source: source
    destination: /webapps/myApp
```

在本範例中，會在 **Install** 事件期間執行下列兩個操作：

1. 將修訂中的 `Config/config.txt` 檔案複製至執行個體上的 `/webapps/Config/config.txt` 路徑。

1. 將修訂 `source` 目錄中的所有檔案都遞迴複製至執行個體上的 `/webapps/myApp` 目錄。

## 「檔案」區段範例
<a name="reference-appspec-file-structure-files-examples"></a>

下列範例顯示如何指定 `files` 區段。雖然這些範例描述了 Windows Server 檔案和目錄 （資料夾） 結構，但它們可以輕鬆適應 Amazon Linux、Ubuntu Server 和 RHEL 執行個體。

**注意**  
只有 EC2/現場部署會使用 `files`區段。它不適用於 AWS Lambda 部署。

在下列範例中，假設這些檔案出現在 `source` 根目錄的套件中：
+ `appspec.yml`
+ `my-file.txt`
+ `my-file-2.txt`
+ `my-file-3.txt`

```
# 1) Copy only my-file.txt to the destination folder c:\temp.
#
files:
  - source: .\my-file.txt
    destination: c:\temp
#
# Result:
#   c:\temp\my-file.txt
#
# ---------------------
#
# 2) Copy only my-file-2.txt and my-file-3.txt to the destination folder c:\temp.
#
files:
  - source: my-file-2.txt
    destination: c:\temp
  - source: my-file-3.txt
    destination: c:\temp
#
# Result:
#   c:\temp\my-file-2.txt
#   c:\temp\my-file-3.txt
#
# ---------------------
#
# 3) Copy my-file.txt, my-file-2.txt, and my-file-3.txt (along with the appspec.yml file) to the destination folder c:\temp.
#
files:
  - source: \
    destination: c:\temp
#
# Result:
#   c:\temp\appspec.yml
#   c:\temp\my-file.txt
#   c:\temp\my-file-2.txt
#   c:\temp\my-file-3.txt
```

在下列範例中，假設 `appspec.yml` 出現在 `source` 根目錄以及名為 `my-folder` 資料夾 (包含三個檔案) 的套件中：
+ `appspec.yml`
+ `my-folder\my-file.txt`
+ `my-folder\my-file-2.txt`
+ `my-folder\my-file-3.txt`

```
# 4) Copy the 3 files in my-folder (but do not copy my-folder itself) to the destination folder c:\temp. 
#
files:
  - source: .\my-folder
    destination: c:\temp
#
# Result:
#   c:\temp\my-file.txt
#   c:\temp\my-file-2.txt
#   c:\temp\my-file-3.txt
#
# ---------------------
#
# 5) Copy my-folder and its 3 files to my-folder within the destination folder c:\temp.
#
files:
  - source: .\my-folder
    destination: c:\temp\my-folder
#
# Result:
#   c:\temp\my-folder\my-file.txt
#   c:\temp\my-folder\my-file-2.txt
#   c:\temp\my-folder\my-file-3.txt
#
# ---------------------
#
# 6) Copy the 3 files in my-folder to other-folder within the destination folder c:\temp.
#
files:
  - source: .\my-folder
    destination: c:\temp\other-folder
#
# Result:
#   c:\temp\other-folder\my-file.txt
#   c:\temp\other-folder\my-file-2.txt
#   c:\temp\other-folder\my-file-3.txt	
#
# ---------------------
#
# 7) Copy only my-file-2.txt and my-file-3.txt to my-folder within the destination folder c:\temp.
#
files:
  - source: .\my-folder\my-file-2.txt
    destination: c:\temp\my-folder
  - source: .\my-folder\my-file-3.txt
    destination: c:\temp\my-folder
#
# Result:
#   c:\temp\my-folder\my-file-2.txt
#   c:\temp\my-folder\my-file-3.txt
#
# ---------------------
#
# 8) Copy only my-file-2.txt and my-file-3.txt to other-folder within the destination folder c:\temp.
#
files:
  - source: .\my-folder\my-file-2.txt
    destination: c:\temp\other-folder
  - source: .\my-folder\my-file-3.txt
    destination: c:\temp\other-folder
#
# Result:
#   c:\temp\other-folder\my-file-2.txt
#   c:\temp\other-folder\my-file-3.txt
#
# ---------------------
#
# 9) Copy my-folder and its 3 files (along with the appspec.yml file) to the destination folder c:\temp. If any of the files already exist on the instance, overwrite them.
#
files:
  - source: \
    destination: c:\temp
file_exists_behavior: OVERWRITE
#
# Result:
#   c:\temp\appspec.yml
#   c:\temp\my-folder\my-file.txt
#   c:\temp\my-folder\my-file-2.txt
#   c:\temp\my-folder\my-file-3.txt
```

# AppSpec 'resources' 區段 （僅限 Amazon ECS 和 AWS Lambda 部署）
<a name="reference-appspec-file-structure-resources"></a>

 AppSpec 檔案 `'resources'`區段中的內容會根據您部署的運算平台而有所不同。Amazon ECS 部署的 `'resources'`區段包含您的 Amazon ECS 任務定義、用於將流量路由到已更新 Amazon ECS 任務集的容器和連接埠，以及其他選用資訊。 AWS Lambda 部署的 `'resources'`區段包含 Lambda 函數的名稱、別名、目前版本和目標版本。

**Topics**
+ [AWS Lambda 部署的 AppSpec 'resources' 區段](#reference-appspec-file-structure-resources-lambda)
+ [Amazon ECS 部署的 AppSpec 'resources' 區段](#reference-appspec-file-structure-resources-ecs)

## AWS Lambda 部署的 AppSpec 'resources' 區段
<a name="reference-appspec-file-structure-resources-lambda"></a>

`'resources'` 區段會指定要部署的 Lambda 函數，並具有下列結構：

YAML：

```
resources:
  - name-of-function-to-deploy:
      type: "AWS::Lambda::Function"
      properties:
        name: name-of-lambda-function-to-deploy
        alias: alias-of-lambda-function-to-deploy
        currentversion: version-of-the-lambda-function-traffic-currently-points-to
        targetversion: version-of-the-lambda-function-to-shift-traffic-to
```

JSON：

```
"resources": [
    {
        "name-of-function-to-deploy" {
            "type": "AWS::Lambda::Function",
            "properties": {
                "name": "name-of-lambda-function-to-deploy",
                "alias": "alias-of-lambda-function-to-deploy",
                "currentversion": "version-of-the-lambda-function-traffic-currently-points-to",
                "targetversion": "version-of-the-lambda-function-to-shift-traffic-to"
            }
        }
    }
]
```

每個屬性皆以字串指定。
+ `name` - 必要。這是要部署的 Lambda 函數名稱。
+ `alias` - 必要。這是 Lambda 函數的別名名稱。
+ `currentversion` - 必要。這是目前指向的 Lambda 函數流量版本。此值必須是有效的正整數。
+ `targetversion` - 必要。這是 Lambda 函數流量的轉移版本。此值必須是有效的正整數。

## Amazon ECS 部署的 AppSpec 'resources' 區段
<a name="reference-appspec-file-structure-resources-ecs"></a>

 `'resources'` 本節指定要部署的 Amazon ECS 服務，並具有下列結構：

YAML：

```
Resources:
  - TargetService:
      Type: AWS::ECS::Service
      Properties:
        TaskDefinition: "task-definition-arn"
        LoadBalancerInfo: 
          ContainerName: "ecs-container-name" 
          ContainerPort: "ecs-application-port"
# Optional properties
        PlatformVersion: "ecs-service-platform-version"
        NetworkConfiguration:
          AwsvpcConfiguration:
            Subnets: ["ecs-subnet-1","ecs-subnet-n"] 
            SecurityGroups: ["ecs-security-group-1","ecs-security-group-n"] 
            AssignPublicIp: "ENABLED | DISABLED"
        CapacityProviderStrategy:
          - Base: integer
            CapacityProvider: "capacityProviderA"
            Weight: integer
          - Base: integer
            CapacityProvider: "capacityProviderB"
            Weight: integer
```

JSON：

```
"Resources": [
    {
        "TargetService": {
            "Type": "AWS::ECS::Service",
            "Properties": {
                "TaskDefinition": "task-definition-arn",
                "LoadBalancerInfo": {
                    "ContainerName": "ecs-container-name",
                    "ContainerPort": "ecs-application-port"
                },
                "PlatformVersion": "ecs-service-platform-version",
                "NetworkConfiguration": {
                    "AwsvpcConfiguration": {
                        "Subnets": [
                            "ecs-subnet-1",
                            "ecs-subnet-n"
                        ],
                        "SecurityGroups": [
                            "ecs-security-group-1",
                            "ecs-security-group-n"
                        ],
                        "AssignPublicIp": "ENABLED | DISABLED"
                    }
                },
                "CapacityProviderStrategy": [
                    {
                        "Base": integer,
                        "CapacityProvider": "capacityProviderA",
                        "Weight": integer
                    },
                    {
                        "Base": integer,
                        "CapacityProvider": "capacityProviderB",
                        "Weight": integer
                    }
                ]
            }
        }
    }
]
```

每個屬性都會以字串指定`ContainerPort`，但 除外，這是數字。
+ `TaskDefinition` - 必要。這是要部署之 Amazon ECS 服務的任務定義。這包含任務定義的 ARN 指定。ARN 格式為 `arn:aws:ecs:aws-region:account-id:task-definition/task-definition-family:task-definition-revision`。如需詳細資訊，請參閱 [Amazon Resource Name (ARNs AWS 和服務命名空間](https://docs.aws.amazon.com/general/latest/gr/aws-arns-and-namespaces.html)。
**注意**  
ARN `:task-definition-revision`的部分是選用的。如果省略，Amazon ECS 會使用任務定義的最新 ACTIVE 修訂。
+ `ContainerName` - 必要。這是包含 Amazon ECS 應用程式的 Amazon ECS 容器名稱。它必須是 Amazon ECS 任務定義中指定的容器。
+ `ContainerPort` - 必要。這是將流量路由到的容器連接埠。
+ `PlatformVersion`：選用。部署的 Amazon ECS 服務中 Fargate 任務的平台版本。如需詳細資訊，請參閱 [AWS Fargate 平台版本](https://docs.aws.amazon.com/AmazonECS/latest/developerguide/platform_versions.html)。如果未指定，預設`LATEST`會使用 。
+  `NetworkConfiguration`：選用。在 `AwsvpcConfiguration` 下，您可以指定下列項目。如需詳細資訊，請參閱《*Amazon ECS Container Service API 參考*》中的 [AwsVpcConfiguration](https://docs.aws.amazon.com/AmazonECS/latest/APIReference/API_AwsVpcConfiguration.html)。
  + `Subnets`：選用。Amazon ECS 服務中一或多個子網路的逗號分隔清單。
  + `SecurityGroups`：選用。Amazon Elastic Container Service 中一或多個安全群組的逗號分隔清單。
  + `AssignPublicIp`：選用。指定 Amazon ECS 服務彈性網路介面是否接收公有 IP 地址的字串。有效值為 `ENABLED` 和 `DISABLED`。
**注意**  
 `NetworkConfiguration` 下的設定必須全部指定，或都不指定。例如，如果您想要指定 `Subnets`，您還必須指定 `SecurityGroups` 和 `AssignPublicIp`。如果未指定，CodeDeploy 會使用目前的網路 Amazon ECS 設定。
+ `CapacityProviderStrategy`：選用。您要用於部署的 Amazon ECS 容量提供者清單。如需詳細資訊，請參閱《[Amazon Elastic Container Service 開發人員指南》中的 Amazon ECS 容量提供者](https://docs.aws.amazon.com/AmazonECS/latest/developerguide/cluster-capacity-providers.html)。 **對於每個容量提供者，您可以指定下列設定。如需這些設定的詳細資訊，請參閱*AWS CloudFormation 《 使用者指南*》中的 [AWS::ECS::ServiceCapacityProviderStrategyItem](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ecs-service-capacityproviderstrategyitem.html) 
  + `Base`：選用。基礎值指定至少要在指定容量提供者上執行多少任務數量。容量提供者策略中只有一個容量提供者可以定義基礎。如果未指定任何值，則會使用預設值 0。
  + `CapacityProvider`：選用。容量提供者的簡短名稱。範例： *capacityProviderA*
  + `Weight`：選用。

    *加權*值會指定應使用指定容量提供者之已啟動任務總數的相對百分比。如果已定義，則會在滿足 `base` 值之後考量 `weight` 值。

    如果未指定任何 `weight` 值，則會使用 `0` 的預設值。在容量提供者策略中指定多個容量供應商時，至少有一個容量供應商必須具有大於零的加權值，且不會使用具有加權 `0` 的任何容量提供者來放置任務。如果您在策略中指定多個容量提供者均具有加權 `0`，則使用容量提供者策略的任何 `RunTask` 或 `CreateService` 動作都會失敗。

     使用加權的一個範例案例為定義策略，該策略包含兩個容量提供者，而且兩者都具有 `1` 加權，則當滿足 `base` 時，任務將會平均分割到兩個容量提供者。依此邏輯，如果您為 *capacityProviderA* 指定 `1` 的權重，並為 *capacityProviderB* 指定 `4` 的權重，則對於使用 *capacityProviderA* 執行的每一個任務而言，四個任務將使用 *capacityProviderB*。

# AppSpec 'permissions' 區段 （僅限 EC2/現場部署）
<a name="reference-appspec-file-structure-permissions"></a>

`'permissions'` 區段指定在將 `'files'` 區段中的檔案和目錄/資料夾複製至執行個體之後，應如何將特殊許可 (如果有的話) 套用至檔案以及目錄/資料夾。您可以指定多個 `object` 說明。此區段為選用。它僅適用於 Amazon Linux、Ubuntu Server 和 RHEL 執行個體。

**注意**  
`'permissions'` 本節僅用於 EC2/現場部署。它不用於 AWS Lambda 或 Amazon ECS 部署。

本區段的結構如下：

```
permissions:
  - object: object-specification
    pattern: pattern-specification
    except: exception-specification
    owner: owner-account-name
    group: group-name
    mode: mode-specification
    acls: 
      - acls-specification 
    context:
      user: user-specification
      type: type-specification
      range: range-specification
    type:
      - object-type
```

說明如下：
+ `object` - 必要。將檔案系統物件複製至執行個體之後，將套用指定之許可的一組檔案系統物件 (檔案或目錄/資料夾)。

  以字串指定 `object`。
+ `pattern` - 選用。指定要套用許可的模式。如果未指定或已指定特殊字元 **"\$1\$1"**，會根據 `type` 將許可套用至所有相符的檔案或目錄。

  使用含引數 ("") 的字串指定 `pattern`。
+ `except` - 選用。指定 `pattern` 例外狀況的任何檔案或目錄。

  以方括號內逗號分隔的字串清單，指定 `except`。
+ `owner` - 選用。`object` 的擁有者名稱。如果未指定，在複製操作之後，所有套用至原始檔案或目錄/資料夾結構的現有擁有者都不會受到影響。

  以字串指定 `owner`。
+ `group` - 選用。`object` 的群組名稱。如果未指定，在複製操作之後，所有套用至原始檔案或目錄/資料夾結構的現有群組都不會受到影響。

  以字串指定 `group`。
+ `mode` - 選用。指定要套用至 之許可的數值`object`。模式設定遵循 Linux chmod 命令語法。
**重要**  
如果值包含前導零，您必須以雙引號括住它，或移除前導零，只保留三個數字。
**注意**  
`mode` 設定**u\$1x**不支援符號表示法，例如 。

  範例：
  + `mode: "0644"` 提供讀取和寫入許可給物件 (6) 的擁有者、群組 (4) 的唯讀許可，以及所有其他使用者的唯讀許可 (4)。
  + `mode: 644` 授予與 相同的許可`mode: "0644"`。
  + `mode: 4755` 設定 setuid 屬性 (4)、將完全控制許可授予擁有者 (7)、將讀取和執行許可授予群組 (5)，以及將讀取和執行許可授予所有其他使用者 (5)。

    如需更多範例，請參閱 Linux chmod 命令文件。

    如果未指定模式，則在複製操作之後，套用至原始檔案或資料夾結構的所有現有模式保持不變。
+ `acls` - 選用。字元字串清單，代表套用至 `object` 的一或多個存取控制清單 (ACL) 項目。例如，**u:bob:rw** 代表 **bob** 使用者的讀取和寫入許可 (如需範例，請參閱 Linux `setfacl` 命令文件中的 ACL 項目格式範例)。您可以指定多個 ACL 項目。如果未指定 `acls`，在複製操作之後，任何套用至原始檔案或目錄/資料夾結構的現有 ACL 都不會受到影響。這些會取代現有的所有 ACL。

  使用依序後接一個空格和一個字串的破折號 (-) 指定 `acls` (例如，`- u:jane:rw`)。如果您有多個 ACL，會在個別的行指定。
**注意**  
設定未命名的使用者、未命名的群組或其他類似的 ACL 項目會導致 AppSpec 檔案失敗。使用 `mode` 指定這些類型的許可。
+ `context` - 選用。對於 Security-Enhanced Linux (SELinux) 啟動的執行個體，是套用到複製物件的安全相關內容標籤清單。標籤指定為包含 `user`、`type` 和 `range` 的索引鍵。(如需詳細資訊，請參閱 SELinux 文件)。每個金鑰都是以字串形式輸入。如果未指定，則在複製作業之後，任何套用至原始檔案或目錄/資料夾結構的現有標籤都不受影響。
  + `user` - 選用。SELinux 使用者。
  + `type` - 選用。SELinux 類型名稱。
  + `range` - 選用。SELinux 範圍的指標。這不會有任何影響，除非機器上有啟用 Multi-Level Security (MLS) 和 Multi-Category Security (MCS)。如果未啟用，`range` 預設為 **s0**。

  以字串指定 `context` (例如，`user: unconfined_u`)。每個 `context` 指定於不同行。
+ `type` - 選用。要套用指定權限的物件類型。`type` 是字串，可設定為 **file** 或 **directory**。如果指定 **file**，許可只會套用到立即包含在複製操作後的 `object` (而非 `object` 本身) 中的檔案。如果指定 **directory**，使用權限會以遞迴方式套用到位於複製操作後 `object` (但不是 `object` 本身) 中任何地方的所有目錄/資料夾。

  以破折號 (-) 後接一個空格和一個字串的形式指定 `type` (例如，`- file`)。

## 「許可」區段範例
<a name="reference-appspec-file-structure-permissions-example"></a>

以下範例顯示如何使用 `object`、`pattern`、`except`、`owner`、`mode` 和 `type` 說明指定 `'permissions'` 區段。此範例僅適用於 Amazon Linux、Ubuntu Server 和 RHEL 執行個體。在這個範例中，假設以下檔案和資料夾都複製到下列階層中的執行個體：

```
/tmp
  `-- my-app
       |-- my-file-1.txt
       |-- my-file-2.txt
       |-- my-file-3.txt
       |-- my-folder-1
       |     |-- my-file-4.txt
       |     |-- my-file-5.txt
       |     `-- my-file-6.txt
       `-- my-folder-2
             |-- my-file-7.txt
             |-- my-file-8.txt
             |-- my-file-9.txt
	           `-- my-folder-3
```

下列 AppSpec 檔案顯示如何在複製這些檔案和資料夾後設定許可：

```
version: 0.0
os: linux
# Copy over all of the folders and files with the permissions they
#  were originally assigned.
files:
  - source: ./my-file-1.txt
    destination: /tmp/my-app
  - source: ./my-file-2.txt
    destination: /tmp/my-app
  - source: ./my-file-3.txt
    destination: /tmp/my-app
  - source: ./my-folder-1
    destination: /tmp/my-app/my-folder-1
  - source: ./my-folder-2
    destination: /tmp/my-app/my-folder-2
# 1) For all of the files in the /tmp/my-app folder ending in -3.txt
#  (for example, just my-file-3.txt), owner = adm, group = wheel, and
#  mode = 464 (-r--rw-r--).
permissions:
  - object: /tmp/my-app
    pattern: "*-3.txt"
    owner: adm
    group: wheel
    mode: 464
    type:
      - file
# 2) For all of the files ending in .txt in the /tmp/my-app
#  folder, but not for the file my-file-3.txt (for example,
#  just my-file-1.txt and my-file-2.txt),
#  owner = ec2-user and mode = 444 (-r--r--r--).
  - object: /tmp/my-app
    pattern: "*.txt"
    except: [my-file-3.txt]
    owner: ec2-user
    mode: 444
    type:
      - file
# 3) For all the files in the /tmp/my-app/my-folder-1 folder except
#  for my-file-4.txt and my-file-5.txt, (for example,
#  just my-file-6.txt), owner = operator and mode = 646 (-rw-r--rw-).
  - object: /tmp/my-app/my-folder-1
    pattern: "**"
    except: [my-file-4.txt, my-file-5.txt]
    owner: operator
    mode: 646
    type:
      - file
# 4) For all of the files that are immediately under
#  the /tmp/my-app/my-folder-2 folder except for my-file-8.txt,
#  (for example, just my-file-7.txt and
#  my-file-9.txt), owner = ec2-user and mode = 777 (-rwxrwxrwx).
  - object: /tmp/my-app/my-folder-2
    pattern: "**"
    except: [my-file-8.txt]
    owner: ec2-user
    mode: 777
    type:
      - file
# 5) For all folders at any level under /tmp/my-app that contain
#  the name my-folder but not
#  /tmp/my-app/my-folder-2/my-folder-3 (for example, just
#  /tmp/my-app/my-folder-1 and /tmp/my-app/my-folder-2),
#  owner = ec2-user and mode = 555 (dr-xr-xr-x).
  - object: /tmp/my-app
    pattern: "*my-folder*"
    except: [tmp/my-app/my-folder-2/my-folder-3]
    owner: ec2-user
    mode: 555
    type:
      - directory
# 6) For the folder /tmp/my-app/my-folder-2/my-folder-3,
#  group = wheel and mode = 564 (dr-xrw-r--).
  - object: /tmp/my-app/my-folder-2/my-folder-3
    group: wheel
    mode: 564
    type:
      - directory
```

產生的許可，如下所示：

```
-r--r--r-- ec2-user root  my-file-1.txt
-r--r--r-- ec2-user root  my-file-2.txt
-r--rw-r-- adm      wheel my-file-3.txt

dr-xr-xr-x ec2-user root  my-folder-1
-rw-r--r-- root     root  my-file-4.txt
-rw-r--r-- root     root  my-file-5.txt
-rw-r--rw- operator root  my-file-6.txt

dr-xr-xr-x ec2-user root  my-folder-2
-rwxrwxrwx ec2-user root  my-file-7.txt
-rw-r--r-- root     root  my-file-8.txt
-rwxrwxrwx ec2-user root  my-file-9.txt

dr-xrw-r-- root     wheel my-folder-3
```

以下範例說明如何指定 `'permissions'` 區段，並新增 `acls` 和 `context` 說明。此範例僅適用於 Amazon Linux、Ubuntu Server 和 RHEL 執行個體。

```
permissions:
  - object: /var/www/html/WordPress
    pattern: "**"
    except: [/var/www/html/WordPress/ReadMe.txt]
    owner: bob
    group: writers
    mode: 644
    acls: 
      - u:mary:rw
      - u:sam:rw
      - m::rw
    context:
      user: unconfined_u
      type: httpd_sys_content_t
      range: s0
    type:
      - file
```

# AppSpec 'hooks' 區段
<a name="reference-appspec-file-structure-hooks"></a>

AppSpec 檔案 `'hooks'`區段中的內容會根據您部署的運算平台而有所不同。EC2/現場部署的 `'hooks'`區段包含將部署生命週期事件掛鉤連結至一或多個指令碼的映射。Lambda 或 Amazon ECS 部署的 `'hooks'`區段指定要在部署生命週期事件期間執行的 Lambda 驗證函數。如果事件勾點不存在，則不會為該事件執行任何操作。只有在您執行指令碼或 Lambda 驗證函數做為部署的一部分時，才需要本節。

**Topics**
+ [Amazon ECS 部署的 AppSpec 'hooks' 區段](#appspec-hooks-ecs)
+ [AWS Lambda 部署的 AppSpec 'hooks' 區段](#appspec-hooks-lambda)
+ [EC2/現場部署的 AppSpec 'hooks' 區段](#appspec-hooks-server)

## Amazon ECS 部署的 AppSpec 'hooks' 區段
<a name="appspec-hooks-ecs"></a>

**Topics**
+ [Amazon ECS 部署的生命週期事件掛鉤清單](#reference-appspec-file-structure-hooks-list-ecs)
+ [在 Amazon ECS 部署中執行掛鉤順序。](#reference-appspec-file-structure-hooks-run-order-ecs)
+ [「勾點」區段的結構](#reference-appspec-file-structure-hooks-section-structure-ecs)
+ [Lambda 'hooks' 函數範例](#reference-appspec-file-structure-hooks-section-structure-ecs-sample-function)

### Amazon ECS 部署的生命週期事件掛鉤清單
<a name="reference-appspec-file-structure-hooks-list-ecs"></a>

 AWS Lambda 勾點是 Lambda 函數，指定的字串位於生命週期事件名稱之後的新行上。每個部署執行每個勾點一次。以下是生命週期事件的說明，您可以在其中在 Amazon ECS 部署期間執行掛鉤。
+  `BeforeInstall` – 用來在建立替代任務集之前執行任務。單一目標群組與原始任務設定相關。如果指定了選用測試接聽程式，則和原始任務設定相關。目前無法轉返。
+  `AfterInstall` – 在建立替代任務集，且其中一個目標群組與其相關聯之後，使用 來執行任務。如果指定了選用測試接聽程式，則和原始任務設定相關。此生命週期事件上的勾點函數結果可以觸發轉返。
+  `AfterAllowTestTraffic` – 在測試接聽程式將流量提供給替代任務集之後，使用 來執行任務。目前的勾點函數結果可以觸發轉返。
+  `BeforeAllowTraffic` – 在第二個目標群組與替代任務集相關聯之後，但在流量轉移到替代任務集之前，使用 來執行任務。此生命週期事件上的勾點函數結果可以觸發轉返。
+  `AfterAllowTraffic` – 在第二個目標群組將流量提供給替代任務集之後，使用 來執行任務。此生命週期事件上的勾點函數結果可以觸發轉返。

如需詳細資訊，請參閱[Amazon ECS 部署期間會發生什麼情況](deployment-steps-ecs.md#deployment-steps-what-happens)及[教學課程：使用驗證測試部署 Amazon ECS 服務](tutorial-ecs-deployment-with-hooks.md)。

### 在 Amazon ECS 部署中執行掛鉤順序。
<a name="reference-appspec-file-structure-hooks-run-order-ecs"></a>

在 Amazon ECS 部署中，事件掛鉤會以下列順序執行：

![\[Amazon ECS 部署中的事件掛鉤順序。\]](http://docs.aws.amazon.com/zh_tw/codedeploy/latest/userguide/images/lifecycle-event-order-ecs.png)


**注意**  
部署中的 **Start**、**Install**、**TestTraffic**、​**AllowTraffic** 和 **End** 事件，無法以指令碼方式處理，這就是它們在本圖表中呈現灰色的原因。

### 「勾點」區段的結構
<a name="reference-appspec-file-structure-hooks-section-structure-ecs"></a>

下列為 `'hooks'` 部分的結構範例。

使用 YAML：

```
Hooks:
  - BeforeInstall: "BeforeInstallHookFunctionName"
  - AfterInstall: "AfterInstallHookFunctionName"
  - AfterAllowTestTraffic: "AfterAllowTestTrafficHookFunctionName"
  - BeforeAllowTraffic: "BeforeAllowTrafficHookFunctionName"
  - AfterAllowTraffic: "AfterAllowTrafficHookFunctionName"
```

使用 JSON：

```
"Hooks": [
		{
			"BeforeInstall": "BeforeInstallHookFunctionName"
		},
		{
			"AfterInstall": "AfterInstallHookFunctionName"
		},
		{
			"AfterAllowTestTraffic": "AfterAllowTestTrafficHookFunctionName"
		},
		{
			"BeforeAllowTraffic": "BeforeAllowTrafficHookFunctionName"
		},
		{
			"AfterAllowTraffic": "AfterAllowTrafficHookFunctionName"
		}
	]
}
```

### Lambda 'hooks' 函數範例
<a name="reference-appspec-file-structure-hooks-section-structure-ecs-sample-function"></a>

使用 `'hooks'`區段指定 CodeDeploy 可以呼叫的 Lambda 函數，以驗證 Amazon ECS 部署。您可以針對 `BeforeInstall`、`AfterInstall`、`BeforeAllowTraffic`、 `AfterAllowTestTraffic`和 `AfterAllowTraffic` 部署生命週期事件使用相同的函數或不同的函數。完成驗證測試後，Lambda `AfterAllowTraffic` 函數會回呼 CodeDeploy，並傳送 `Succeeded` 或 `Failed` 的結果。

**重要**  
如果 Lambda 驗證函數在一小時內未通知 CodeDeploy，則部署會被視為失敗。

 叫用 Lambda 勾點函數之前，必須使用 `putLifecycleEventHookExecutionStatus`命令通知伺服器部署 ID 和生命週期事件勾點執行 ID。

 以下是以 Node.js 編寫的範例 Lambda 勾點函數。

```
'use strict';

const aws = require('aws-sdk');
const codedeploy = new aws.CodeDeploy({apiVersion: '2014-10-06'});

exports.handler = (event, context, callback) => {
    //Read the DeploymentId from the event payload.
    var deploymentId = event.DeploymentId;

    //Read the LifecycleEventHookExecutionId from the event payload
    var lifecycleEventHookExecutionId = event.LifecycleEventHookExecutionId;

    /*
     Enter validation tests here.
    */

    // Prepare the validation test results with the deploymentId and
    // the lifecycleEventHookExecutionId for CodeDeploy.
    var params = {
        deploymentId: deploymentId,
        lifecycleEventHookExecutionId: lifecycleEventHookExecutionId,
        status: 'Succeeded' // status can be 'Succeeded' or 'Failed'
    };
    
    // Pass CodeDeploy the prepared validation test results.
    codedeploy.putLifecycleEventHookExecutionStatus(params, function(err, data) {
        if (err) {
            // Validation failed.
            callback('Validation test failed');
        } else {
            // Validation succeeded.
            callback(null, 'Validation test succeeded');
        }
    });
};
```

## AWS Lambda 部署的 AppSpec 'hooks' 區段
<a name="appspec-hooks-lambda"></a>

**Topics**
+ [AWS Lambda 部署的生命週期事件掛鉤清單](#reference-appspec-file-structure-hooks-list-lambda)
+ [在 Lambda 函數版本部署中執行掛鉤順序](#reference-appspec-file-structure-hooks-run-order-lambda)
+ [「勾點」區段的結構](#reference-appspec-file-structure-hooks-section-structure-lambda)
+ [Lambda 'hooks' 函數範例](#reference-appspec-file-structure-hooks-section-structure-lambda-sample-function)

### AWS Lambda 部署的生命週期事件掛鉤清單
<a name="reference-appspec-file-structure-hooks-list-lambda"></a>

 AWS Lambda 勾點是 Lambda 函數，指定的字串位於生命週期事件名稱之後的新行上。每個部署執行每個勾點一次。以下是可用於 AppSpec 檔案之勾點的描述。
+ **BeforeAllowTraffic** – 在流量轉移到已部署的 Lambda 函數版本之前，使用 執行任務。
+ **AfterAllowTraffic** – 用於在所有流量轉移到已部署的 Lambda 函數版本後執行任務。

### 在 Lambda 函數版本部署中執行掛鉤順序
<a name="reference-appspec-file-structure-hooks-run-order-lambda"></a>

在無伺服器 Lambda 函數版本部署中，事件掛鉤會以下列順序執行：

![\[Lambda 部署中的事件掛鉤順序。\]](http://docs.aws.amazon.com/zh_tw/codedeploy/latest/userguide/images/lifecycle-event-order-lambda.png)


**注意**  
部署中的 **Start**、**AllowTraffic** 和 **End** 事件無法以指令碼處理，這就是它們在本圖表中呈現灰色的原因。

### 「勾點」區段的結構
<a name="reference-appspec-file-structure-hooks-section-structure-lambda"></a>

下列為 'hooks' 部分的結構範例。

使用 YAML：

```
hooks:
   - BeforeAllowTraffic: BeforeAllowTrafficHookFunctionName
   - AfterAllowTraffic: AfterAllowTrafficHookFunctionName
```

使用 JSON：

```
"hooks": [{
    "BeforeAllowTraffic": "BeforeAllowTrafficHookFunctionName"
    },
    {
    "AfterAllowTraffic": "AfterAllowTrafficHookFunctionName"
}]
```

### Lambda 'hooks' 函數範例
<a name="reference-appspec-file-structure-hooks-section-structure-lambda-sample-function"></a>

使用 'hooks' 區段指定 CodeDeploy 可以呼叫的 Lambda 函數，以驗證 Lambda 部署。您可以針對 `BeforeAllowTraffic`和 `AfterAllowTraffic` 部署生命週期事件使用相同的函數或不同的函數。驗證測試完成後，Lambda 驗證函數會回呼 CodeDeploy 並交付 `Succeeded`或 的結果`Failed`。

**重要**  
如果 Lambda 驗證函數在一小時內未通知 CodeDeploy，則部署會被視為失敗。

 叫用 Lambda 勾點函數之前，必須使用 `putLifecycleEventHookExecutionStatus`命令通知伺服器部署 ID 和生命週期事件勾點執行 ID。

 以下是以 Node.js 編寫的範例 Lambda 勾點函數。

```
'use strict';

const aws = require('aws-sdk');
const codedeploy = new aws.CodeDeploy({apiVersion: '2014-10-06'});

exports.handler = (event, context, callback) => {
    //Read the DeploymentId from the event payload.
    var deploymentId = event.DeploymentId;

    //Read the LifecycleEventHookExecutionId from the event payload
    var lifecycleEventHookExecutionId = event.LifecycleEventHookExecutionId;

    /*
     Enter validation tests here.
    */

    // Prepare the validation test results with the deploymentId and
    // the lifecycleEventHookExecutionId for CodeDeploy.
    var params = {
        deploymentId: deploymentId,
        lifecycleEventHookExecutionId: lifecycleEventHookExecutionId,
        status: 'Succeeded' // status can be 'Succeeded' or 'Failed'
    };
    
    // Pass CodeDeploy the prepared validation test results.
    codedeploy.putLifecycleEventHookExecutionStatus(params, function(err, data) {
        if (err) {
            // Validation failed.
            callback('Validation test failed');
        } else {
            // Validation succeeded.
            callback(null, 'Validation test succeeded');
        }
    });
};
```

## EC2/現場部署的 AppSpec 'hooks' 區段
<a name="appspec-hooks-server"></a>

**Topics**
+ [生命週期事件掛鉤的清單](#reference-appspec-file-structure-hooks-list)
+ [生命週期事件掛鉤可用性](#reference-appspec-file-structure-hooks-availability)
+ [部署中掛鉤的執行順序](#reference-appspec-file-structure-hooks-run-order)
+ [「勾點」區段的結構](#reference-appspec-file-structure-hooks-section-structure)
+ [參考掛鉤指令碼中的檔案](#codedeploy-agent-working-directory)
+ [勾點的環境變數可用性](#reference-appspec-file-structure-environment-variable-availability)
+ [勾點範例](#reference-appspec-file-structure-hooks-example)

### 生命週期事件掛鉤的清單
<a name="reference-appspec-file-structure-hooks-list"></a>

EC2/現場部署掛鉤會在每次部署至執行個體時執行一次。您可以指定一或多個指令碼以在勾點中執行。生命週期事件的每個勾點是在不同行上以字串指定。以下是可用於 AppSpec 檔案之勾點的描述。

如需有關哪些生命週期事件勾點對於哪些部署和復原類型有效的詳細資訊，請參閱[生命週期事件掛鉤可用性](#reference-appspec-file-structure-hooks-availability)。
+ `ApplicationStop` – 即使在下載應用程式修訂版之前，也會發生此部署生命週期事件。在準備部署時，您可以指定這個事件的指令碼從容地停止應用程式，或移除目前已安裝的套件。用於此部署生命週期事件的 AppSpec 檔案和指令碼來自先前成功部署的應用程式修訂版。
**注意**  
在部署到執行個體之前，執行個體上不存在 AppSpec 檔案。因此，`ApplicationStop` 勾點不會在您第一次部署到執行個體時執行。您可以在第二次部署到執行個體時使用 `ApplicationStop` 勾點。

   為了判斷上次成功部署應用程式修訂版的位置，CodeDeploy 代理程式會查詢 `deployment-group-id_last_successful_install` 檔案中列出的位置。此檔案位於：

   `/opt/codedeploy-agent/deployment-root/deployment-instructions` Amazon Linux、Ubuntu Server 和 RHEL Amazon EC2 執行個體上的 資料夾。

  `C:\ProgramData\Amazon\CodeDeploy\deployment-instructions` Windows Server Amazon EC2 執行個體上的 資料夾。

  若要排除部署在 `ApplicationStop` 部署生命週期事件期間失敗的問題，請參閱[故障診斷失敗的 ApplicationStop、 BeforeBlockTraffic 或 AfterBlockTraffic 部署生命週期事件](troubleshooting-deployments.md#troubleshooting-deployments-lifecycle-event-failures)。
+ `DownloadBundle` – 在此部署生命週期事件期間，CodeDeploy 代理程式會將應用程式修訂檔案複製到暫時位置：

  `/opt/codedeploy-agent/deployment-root/deployment-group-id/deployment-id/deployment-archive` Amazon Linux、Ubuntu Server 和 RHEL Amazon EC2 執行個體上的 資料夾。

  `C:\ProgramData\Amazon\CodeDeploy\deployment-group-id\deployment-id\deployment-archive` Windows Server Amazon EC2 執行個體上的 資料夾。

  此事件保留給 CodeDeploy 代理程式，無法用於執行指令碼。

  若要排除部署在 `DownloadBundle` 部署生命週期事件期間失敗的問題，請參閱[故障診斷錯誤訊息為「UnknownError：未開啟讀取」的已失敗 DownloadBundle 部署生命週期事件](troubleshooting-deployments.md#troubleshooting-deployments-downloadbundle)。
+ `BeforeInstall` – 您可以使用此部署生命週期事件來預先安裝任務，例如解密檔案和建立目前版本的備份。
+ `Install` – 在此部署生命週期事件期間，CodeDeploy 代理程式會將修訂檔案從暫時位置複製到最終目的地資料夾。此事件保留給 CodeDeploy 代理程式，無法用於執行指令碼。
+ `AfterInstall` – 您可以將此部署生命週期事件用於設定應用程式或變更檔案許可等任務。
+ `ApplicationStart` – 您通常會使用此部署生命週期事件來重新啟動在 期間停止的服務`ApplicationStop`。
+ `ValidateService` – 這是最後一個部署生命週期事件。這用於驗證部署已順利完成。
+ `BeforeBlockTraffic` – 在從負載平衡器取消註冊執行個體之前，您可以使用此部署生命週期事件在執行個體上執行任務。

  若要排除部署在 `BeforeBlockTraffic` 部署生命週期事件期間失敗的問題，請參閱[故障診斷失敗的 ApplicationStop、 BeforeBlockTraffic 或 AfterBlockTraffic 部署生命週期事件](troubleshooting-deployments.md#troubleshooting-deployments-lifecycle-event-failures)。
+ `BlockTraffic` – 在此部署生命週期事件期間，網際網路流量會遭到封鎖，無法存取目前正在服務流量的執行個體。此事件保留給 CodeDeploy 代理程式，無法用於執行指令碼。
+ `AfterBlockTraffic` – 在從個別負載平衡器取消註冊執行個體之後，您可以使用此部署生命週期事件在執行個體上執行任務。

  若要排除部署在 `AfterBlockTraffic` 部署生命週期事件期間失敗的問題，請參閱[故障診斷失敗的 ApplicationStop、 BeforeBlockTraffic 或 AfterBlockTraffic 部署生命週期事件](troubleshooting-deployments.md#troubleshooting-deployments-lifecycle-event-failures)。
+ `BeforeAllowTraffic` – 您可以在執行個體註冊負載平衡器之前，使用此部署生命週期事件在執行個體上執行任務。
+ `AllowTraffic` – 在此部署生命週期事件期間，允許網際網路流量在部署之後存取執行個體。此事件保留給 CodeDeploy 代理程式，無法用於執行指令碼。
+ `AfterAllowTraffic` – 在執行個體向負載平衡器註冊之後，您可以使用此部署生命週期事件在執行個體上執行任務。

### 生命週期事件掛鉤可用性
<a name="reference-appspec-file-structure-hooks-availability"></a>

下表列出生命週期事件勾點可用於每一個部署及復原案例。


| 生命週期事件名稱 | Auto Scaling 啟動部署1 | Auto Scaling 終止部署1 | 就地部署2 | 藍/綠部署：原始執行個體 | 藍/綠部署：取代執行個體 | 藍/綠部署復原：原始執行個體 | 藍/綠部署復原：取代執行個體 | 
| --- | --- | --- | --- | --- | --- | --- | --- | 
| ApplicationStop | ✓ | ✓ | ✓ |  | ✓ |  |  | 
| DownloadBundle3 | ✓ |  | ✓ |  | ✓ |  |  | 
| BeforeInstall | ✓ |  | ✓ |  | ✓ |  |  | 
| Install3 | ✓ |  | ✓ |  | ✓ |  |  | 
| AfterInstall | ✓ |  | ✓ |  | ✓ |  |  | 
| ApplicationStart | ✓ |  | ✓ |  | ✓ |  |  | 
| ValidateService | ✓ |  | ✓ |  | ✓ |  |  | 
| BeforeBlockTraffic |  | ✓ | ✓ | ✓ |  |  | ✓ | 
| BlockTraffic3 |  | ✓ | ✓ | ✓ |  |  | ✓ | 
| AfterBlockTraffic |  | ✓ | ✓ | ✓ |  |  | ✓ | 
| BeforeAllowTraffic | ✓ |  | ✓ |  | ✓ | ✓ |  | 
| AllowTraffic3 | ✓ |  | ✓ |  | ✓ | ✓ |  | 
| AfterAllowTraffic | ✓ |  | ✓ |  | ✓ | ✓ |  | 
|  1 如需 Amazon EC2 Auto Scaling 部署的相關資訊，請參閱 [Amazon EC2 Auto Scaling 如何與 CodeDeploy 搭配使用](integrations-aws-auto-scaling.md#integrations-aws-auto-scaling-behaviors)。 2 也適用於就地部署的復原。 3 預留給 CodeDeploy 操作。無法用於執行指令碼。  | 

### 部署中掛鉤的執行順序
<a name="reference-appspec-file-structure-hooks-run-order"></a>

**Auto Scaling 啟動部署**

在 Auto Scaling 啟動部署期間，CodeDeploy 會依下列順序執行事件掛鉤。

如需 Auto Scaling 啟動部署的詳細資訊，請參閱 [Amazon EC2 Auto Scaling 如何與 CodeDeploy 搭配使用](integrations-aws-auto-scaling.md#integrations-aws-auto-scaling-behaviors)。

![\[Auto Scaling 啟動部署期間的事件掛鉤順序。\]](http://docs.aws.amazon.com/zh_tw/codedeploy/latest/userguide/images/lifecycle-event-order-scale-out.png)


**注意**  
部署中的 **Start**、**DownloadBundle**、**Install**、**AllowTraffic** 和 **End** 事件無法編寫指令碼，因此在此圖表中會以灰色顯示。不過，您可以編輯 AppSpec 檔案的 `'files'`區段，以指定**安裝**事件期間安裝的項目。

**Auto Scaling 終止部署**

在 Auto Scaling 終止部署期間，CodeDeploy 會依下列順序執行事件掛鉤。

如需 Auto Scaling 終止部署的詳細資訊，請參閱 [在 Auto Scaling 縮減事件期間啟用終止部署](integrations-aws-auto-scaling.md#integrations-aws-auto-scaling-behaviors-hook-enable)。

![\[Auto Scaling 終止部署期間的事件掛鉤順序。\]](http://docs.aws.amazon.com/zh_tw/codedeploy/latest/userguide/images/lifecycle-event-order-scale-in.png)


**注意**  
部署中的 **Start**、**BlockTraffic** 和 **End** 事件無法編寫指令碼，因此在此圖表中會以灰色顯示。

**就地部署**：

在就地部署中，包括就地部署的復原，事件勾點以下列順序執行：

**注意**  
對於就地部署，與封鎖和允許流量相關的六個掛鉤僅適用於部署群組中從 Elastic Load Balancing 指定 Classic Load Balancer、Application Load Balancer 或 Network Load Balancer。

![\[在就地部署復原期間的事件掛鉤順序。\]](http://docs.aws.amazon.com/zh_tw/codedeploy/latest/userguide/images/lifecycle-event-order-in-place.png)


**注意**  
部署中的 **Start**、**DownloadBundle**、**Install** 和 **End** 事件無法以指令碼方式處理，這就是它們在本圖表中呈現灰色的原因。不過，您可以編輯 AppSpec 檔案的 `'files'`區段，以指定**安裝**事件期間安裝的項目。

**藍/綠部署**

在藍/綠部署中，事件勾點以下列順序執行：

![\[藍/綠部署中的事件掛鉤順序。\]](http://docs.aws.amazon.com/zh_tw/codedeploy/latest/userguide/images/lifecycle-event-order-blue-green.png)


**注意**  
部署中的 **Start**、**DownloadBundle**​、**Install**、​**BlockTraffic**、​**AllowTraffic** 和 **End** 事件，無法以指令碼方式處理，這就是它們在本圖表中呈現灰色的原因。不過，您可以編輯 AppSpec 檔案的 'files' 區段，以指定**安裝**事件期間安裝的項目。

### 「勾點」區段的結構
<a name="reference-appspec-file-structure-hooks-section-structure"></a>

`'hooks'` 區段的結構如下：

```
hooks:
   deployment-lifecycle-event-name:
     - location: script-location
       timeout: timeout-in-seconds
       runas: user-name
```

您可以在 **hook** 項目中，在部署生命週期事件名稱後包含下列元素：

** location **  
必要. 修訂版指令碼檔案的套件組合位置。您在 `hooks`區段中指定的指令碼位置是相對於應用程式修訂版套件的根目錄。如需詳細資訊，請參閱[規劃 CodeDeploy 的修訂](application-revisions-plan.md)。

** timeout **  
選用。指令碼被視為失敗前允許執行的秒數。預設為 3600 秒 (1 小時)。  
3600秒 (1小時) 是允許為每個部署生命週期事件執行指令碼時間上限。如果指令碼超過此限制，部署會停止，且部署到執行個體會失敗。請確認每一個部署生命週期事件內所有的指令碼所指定的 **timeout** 總秒數不超過這個限制。

** runas **  
選用。當執行指令碼時要模擬的使用者。根據預設，這是在執行個體上執行的 CodeDeploy 代理程式。CodeDeploy 不會儲存密碼，因此如果 **Runas** 使用者需要密碼，就無法模擬使用者。此元素僅適用於 Amazon Linux 和 Ubuntu Server 執行個體。

### 參考掛鉤指令碼中的檔案
<a name="codedeploy-agent-working-directory"></a>

如果您要將指令碼連接到 CodeDeploy 生命週期事件，如 中所述[AppSpec 'hooks' 區段](#reference-appspec-file-structure-hooks)，並且想要在指令碼中參考檔案 （例如 `helper.sh`)，則需要`helper.sh`使用下列命令來指定 ：
+ （建議） 絕對路徑。請參閱 [使用絕對路徑](#codedeploy-agent-working-dir-absolute)。
+ 相對路徑。請參閱 [使用相對路徑](#codedeploy-agent-working-dir-relative)。

#### 使用絕對路徑
<a name="codedeploy-agent-working-dir-absolute"></a>

若要使用檔案的*絕對*路徑來參考檔案，您可以：
+ 在 `destination` 屬性的 AppSpec 檔案 `files`區段中指定絕對路徑。然後，在掛接指令碼中指定相同的絕對路徑。如需詳細資訊，請參閱[AppSpec 'files' 區段 （僅限 EC2/內部部署部署）](reference-appspec-file-structure-files.md)。
+ 在掛鉤指令碼中指定動態絕對路徑。如需詳細資訊，請參閱[部署封存位置](#codedeploy-agent-working-dir-archive)。

**部署封存位置**

在 [DownloadBundle](#reference-appspec-file-structure-hooks-list) 生命週期事件期間，CodeDeploy 代理程式會將部署的[修訂](application-revisions.md)擷取到具有下列格式的目錄：

`root-directory/deployment-group-id/deployment-id/deployment-archive`

路徑的*根目錄*部分一律設定為下表所示的預設值，或由 `:root_dir` 組態設定控制。如需組態設定的詳細資訊，請參閱 [CodeDeploy 代理程式組態參考](reference-agent-configuration.md)。


| 客服人員平台 | 預設根目錄 | 
| --- | --- | 
| Linux – 所有 rpm 分佈 |  /opt/codedeploy-agent/deployment-root  | 
| Ubuntu Server – 所有 Deb 分佈 |  /opt/codedeploy-agent/deployment-root  | 
| Windows Server |  %ProgramData%\$1Amazon\$1CodeDeploy  | 

從您的掛接指令碼中，您可以使用根目錄路徑和 `DEPLOYMENT_ID`和 `DEPLOYMENT_GROUP_ID`環境變數來存取目前的部署封存。如需您可以使用之變數的詳細資訊，請參閱 [勾點的環境變數可用性](#reference-appspec-file-structure-environment-variable-availability)。

例如，以下說明如何存取位於 Linux 修訂版根目錄`data.json`的檔案：

```
#!/bin/bash

rootDirectory="/opt/codedeploy-agent/deployment-root" # note: this will be different if you
                                                      # customize the :root_dir configuration
dataFile="$rootDirectory/$DEPLOYMENT_GROUP_ID/$DEPLOYMENT_ID/deployment-archive/data.json"
data=$(cat dataFile)
```

另一個範例是，以下是如何在 Windows 上使用 Powershell 存取位於修訂根目錄`data.json`的檔案：

```
$rootDirectory="$env:ProgramData\Amazon\CodeDeploy" # note: this will be different if you
                                                    # customize the :root_dir configuration
$dataFile="$rootDirectory\$env:DEPLOYMENT_GROUP_ID\$env:DEPLOYMENT_ID\deployment-archive\data.json"
$data=(Get-Content $dataFile)
```

#### 使用相對路徑
<a name="codedeploy-agent-working-dir-relative"></a>

若要使用檔案的*相對*路徑來參考檔案，您需要知道 CodeDeploy 代理程式的工作目錄。檔案路徑與此目錄相對。

下表顯示 CodeDeploy 代理程式每個支援平台的工作目錄。

[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_tw/codedeploy/latest/userguide/reference-appspec-file-structure-hooks.html)

### 勾點的環境變數可用性
<a name="reference-appspec-file-structure-environment-variable-availability"></a>

在每個部署生命週期事件期間，勾點指令碼能存取以下環境變數：

** APPLICATION\$1NAME **  
CodeDeploy 中屬於目前部署一部分的應用程式名稱 （例如 `WordPress_App`)。

** DEPLOYMENT\$1ID **  
ID CodeDeploy 已指派給目前的部署 （例如，`d-AB1CDEF23`)。

** DEPLOYMENT\$1GROUP\$1NAME **  
CodeDeploy 中屬於目前部署一部分的部署群組名稱 （例如 `WordPress_DepGroup`)。

** DEPLOYMENT\$1GROUP\$1ID **  
CodeDeploy 中屬於目前部署一部分的部署群組 ID （例如 `b1a2189b-dd90-4ef5-8f40-4c1c5EXAMPLE`)。

** LIFECYCLE\$1EVENT **  
目前部署生命週期事件的名稱 (例如，`AfterInstall`)。

這些環境變數在每個部署生命週期事件的本機。

 根據部署套件的來源，還有其他環境變數可用於掛接指令碼：

**Amazon S3 的套件**
+ **BUNDLE\$1BUCKET**

  下載部署套件的 Amazon S3 儲存貯體名稱 （例如 `my-s3-bucket`)。
+ **BUNDLE\$1KEY**

  Amazon S3 儲存貯體中下載套件的物件金鑰 （例如 `WordPress_App.zip`)。
+ **BUNDLE\$1VERSION**

  套件的物件版本 （例如，`3sL4kqtJlcpXroDTDmJ+rmSpXd3dIbrHY+MTRCxf3vjVBH40Nr8X8gdRQBpUMLUo`)。只有在 Amazon S3 儲存貯體已啟用[物件版本控制](https://docs.aws.amazon.com/AmazonS3/latest/userguide/Versioning.html)時，才會設定此變數。
+ **BUNDLE\$1ETAG**

  套件的物件標籤 （例如 `b10a8db164e0754105b7a99be72e3fe5-4`)。

**GitHub 的套件**
+ **BUNDLE\$1COMMIT**

  Git 產生的套件的 SHA256 遞交雜湊 （例如，`d2a84f4b8b650937ec8f73cd8be2c74add5a911ba64df27458ed8229da804a26`)。

如果 **DEPLOYMENT\$1GROUP\$1NAME** 的值等於 `Staging`，以下指令碼會變更Apache HTTP 伺服機上的接聽連接埠到 9090 以代替 80。這個指令碼必須在 `BeforeInstall` 部署生命週期事件期間叫用：

```
if [ "$DEPLOYMENT_GROUP_NAME" == "Staging" ]
then
    sed -i -e 's/Listen 80/Listen 9090/g' /etc/httpd/conf/httpd.conf
fi
```

如果 **DEPLOYMENT\$1GROUP\$1NAME** 環境變數的值等於 `Staging`，以下指令碼範例會將錯誤日誌中所記錄的詳細資訊等級，從警告變更為偵錯。這個指令碼必須在 `BeforeInstall` 部署生命週期事件期間叫用：

```
if [ "$DEPLOYMENT_GROUP_NAME" == "Staging" ]
then
    sed -i -e 's/LogLevel warn/LogLevel debug/g' /etc/httpd/conf/httpd.conf
fi
```

以下指令碼範例取代被指定的網頁文字，其顯示這些環境變數的值。這個指令碼必須在 `AfterInstall` 部署生命週期事件期間叫用：

```
#!/usr/bin/python

import os
 
strToSearch="<h2>This application was deployed using CodeDeploy.</h2>"
strToReplace="<h2>This page for "+os.environ['APPLICATION_NAME']+" application and "+os.environ['DEPLOYMENT_GROUP_NAME']+" deployment group with "+os.environ['DEPLOYMENT_GROUP_ID']+" deployment group ID was generated by a "+os.environ['LIFECYCLE_EVENT']+" script during "+os.environ['DEPLOYMENT_ID']+" deployment.</h2>"
 
fp=open("/var/www/html/index.html","r")
buffer=fp.read()
fp.close()
 
fp=open("/var/www/html/index.html","w")
fp.write(buffer.replace(strToSearch,strToReplace))
fp.close()
```

### 勾點範例
<a name="reference-appspec-file-structure-hooks-example"></a>

這裡有一個 **hooks** 輸入項目的範例，其為 `AfterInstall` 生命週期事件指定兩個勾點。

```
hooks:
   AfterInstall:
     - location: Scripts/RunResourceTests.sh
       timeout: 180
     - location: Scripts/PostDeploy.sh
       timeout: 180
```

`Scripts/RunResourceTests.sh`指令碼在部署程序的 `AfterInstall` 階段期間執行。如果它需要超過 180 秒 (3分鐘) 去執行指令碼，則表示部署是不成功的。

您在 'hooks' 部分指定的指令碼位置，與應用程式修訂版套件組合的根目錄相關。在前述案例中，名為 `RunResourceTests.sh` 的檔案位於名為 `Scripts` 的目錄中。`Scripts` 目錄位於套件組合的根層級。如需詳細資訊，請參閱[規劃 CodeDeploy 的修訂](application-revisions-plan.md)。