

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

# 使用 AWSTOE 组件文档框架创建自定义组件
<a name="toe-use-documents"></a>

要使用 AWS Task Orchestrator and Executor (AWSTOE) 组件框架构建组件，必须提供一个基于 YAML 的文档，该文档表示适用于您创建的组件的阶段和步骤。 AWS 服务 当他们创建新的 Amazon 系统映像 (AMI) 或容器映像时，请使用您的组件。

**Topics**
+ [组件文档工作流程](#component-doc-workflow)
+ [组件日志](#component-logging)
+ [输入和输出链](#document-chaining)
+ [文档架构和定义](#document-schema)
+ [文档示例](#document-example)
+ [在自定义组件文档中使用变量](toe-user-defined-variables.md)
+ [在中使用条件构造 AWSTOE](toe-conditional-constructs.md)
+ [在 AWSTOE 组件文档中使用比较运算符](toe-comparison-operators.md)
+ [在 AWSTOE 组件文档中使用逻辑运算符](toe-logical-operators.md)
+ [在中使用循环结构 AWSTOE](toe-looping-constructs.md)

## 组件文档工作流程
<a name="component-doc-workflow"></a>

 AWSTOE 组件文档使用阶段和步骤对相关任务进行分组，并将这些任务组织成组件的逻辑工作流程。

**提示**  
使用您的组件构建映像的服务可能会实施有关构建过程使用哪些阶段，以及何时允许这些阶段运行的规则。您在设计组件时，请务必考虑这一点。

**阶段**  
阶段表示您的工作流程在映像构建过程中的进展。例如，Image Builder 服务在其*构建阶段*对其生成的映像使用 `build` 和 `validate` 阶段。它在*测试阶段*使用 `test` 和 `container-host-test` 阶段来确保在创建最终 AMI 或分发容器映像之前，映像快照或容器映像产生预期的结果。

当组件运行时，每个阶段的关联命令将按照它们在组件文档中出现的顺序进行应用。

**阶段规则**
+ 每个阶段名称在文档中必须是唯一的。
+ 您可以在文档中定义多个阶段。
+ 您必须在文档中至少包含以下至少一个阶段：
  + **构建** — 对于 Image Builder，此阶段通常在*构建阶段*使用。
  + **验证** — 对于 Image Builder，此阶段通常在*构建阶段*使用。
  + **测试** — 对于 Image Builder，此阶段通常在*测试阶段*使用。
+ 阶段始终按照文档中定义的顺序运行。中为 AWSTOE 命令指定它们的顺序 AWS CLI 无效。

**Steps**  
步骤是定义每个阶段中的工作流程的各个工作单元。步骤按先后顺序运行。但是，一个步骤的输入或输出也可以作为输入馈送到后续步骤中。这就是所谓的“链”。

**步骤规则**
+ 步骤名称对于阶段来说必须是唯一的。
+ 步骤必须使用可返回退出代码的支持的操作（操作模块）。

  有关支持的操作模块、其工作原理、 input/output 值和示例的完整列表，请参阅[AWSTOE 组件管理器支持的操作模块](toe-action-modules.md)。

## 组件日志
<a name="component-logging"></a>

AWSTOE 每次运行组件时，都会在 EC2 实例上创建一个新的日志文件夹，用于构建和测试新映像。对于容器映像，日志文件夹存储在容器中。

为了帮助在图像创建过程中出现问题时进行故障排除，在运行组件时 AWSTOE 创建的输入文档和所有输出文件都存储在日志文件夹中。

日志文件夹名称由以下部分组成：

1. **日志目录** — 当服务运行 AWSTOE 组件时，它会与该命令的其他设置一起传入日志目录。在以下示例中，我们展示了 Image Builder 使用的日志文件格式。
   + **Linux 和 macOS**：`/var/lib/amazon/toe/`
   + **Windows**：`$env:ProgramFiles\Amazon\TaskOrchestratorAndExecutor\`

1. **文件前缀** — 这是用于所有组件的标准前缀：“`TOE_`”。

1. **运行时间** — 这是一个 YYYY-MM-DD \$1HH-MM-SS\$1UTC-0 格式的时间戳。

1. **执行 ID**-这是 AWSTOE 运行一个或多个组件时分配的 GUID。

示例：`/var/lib/amazon/toe/TOE_2021-07-01_12-34-56_UTC-0_a1bcd2e3-45f6-789a-bcde-0fa1b2c3def4`

AWSTOE 将以下核心文件存储在日志文件夹中：

**输入文件**
+ **document.yaml** — 用作命令输入的文档。组件运行后，该文件将作为构件存储。

**输出文件**
+ **application.log** — 应用程序日志包含来自 AWSTOE 、带有时间戳的调试级别信息，这些信息有关组件运行时发生的情况。
+ **detailedoutput.json** — 此 JSON 文件包含有关组件运行时适用于组件的所有文档、阶段和步骤的运行状态、输入、输出和失败的详细信息。
+ **console.log** — 控制台日志包含组件运行时 AWSTOE 写入控制台的所有标准输出 (stdout) 和标准错误 (stderr) 信息。
+ **chaining.json** — 此 JSON 文件表示 AWSTOE 应用于解析链接表达式的优化。

**注意**  
日志文件夹还可能包含此处未涵盖的其他临时文件。

## 输入和输出链
<a name="document-chaining"></a>

 AWSTOE 配置管理应用程序提供了一种通过编写以下格式的参考文献来链接输入和输出的功能：

`{{ phase_name.step_name.inputs/outputs.variable }}`

或者

`{{ phase_name.step_name.inputs/outputs[index].variable }}`

通过使用链功能，您可以回收代码并提高文档的可维护性。

**链式规则**
+ 只能在每个步骤的输入部分中使用链表达式。
+ 具有链表达式的语句必须用引号引起来。例如：
  + **无效的表达式**：`echo {{ phase.step.inputs.variable }}`
  + **有效的表达式**：`"echo {{ phase.step.inputs.variable }}"`
  + **有效的表达式**：`'echo {{ phase.step.inputs.variable }}'`
+ 链表达式可以引用同一文档中的其他步骤和阶段的变量。但是，调用服务可能有一些规则，要求链表达式只能在单个阶段的上下文中运行。例如，Image Builder 不支持从*构建阶段*到*测试阶段*的链接，因为它独立运行每个阶段。
+ 链表达式中的索引从零开始。索引以零 (0) 开头，以引用第一个元素。

**示例**

要在以下示例步骤的第二个条目中引用源变量，链模式为 `{{ build.SampleS3Download.inputs[1].source }}`。

```
phases:
  - name: 'build'
    steps:
      - name: SampleS3Download
        action: S3Download
        timeoutSeconds: 60
        onFailure: Abort
        maxAttempts: 3
        inputs:
          - source: 's3://sample-bucket/sample1.ps1'
            destination: 'C:\sample1.ps1'
          - source: 's3://sample-bucket/sample2.ps1'
            destination: 'C:\sample2.ps1'
```

要引用以下示例步骤的输出变量（等于“Hello”），链模式为 `{{ build.SamplePowerShellStep.outputs.stdout }}`。

```
phases:
  - name: 'build'
    steps:
      - name: SamplePowerShellStep
        action: ExecutePowerShell
        timeoutSeconds: 120
        onFailure: Abort
        maxAttempts: 3
        inputs:
          commands:
            - 'Write-Host "Hello"'
```

## 文档架构和定义
<a name="document-schema"></a>

以下是文档的 YAML 架构。

```
name: (optional)
description: (optional)
schemaVersion: "string"

phases:
  - name: "string"
    steps:
      - name: "string"
        action: "string"
        timeoutSeconds: integer
        onFailure: "Abort|Continue|Ignore"
        maxAttempts: integer
        inputs:
```

文档的架构定义如下所示。


| 字段 | 描述 | Type | 必需 | 
| --- | --- | --- | --- | 
| name | 文档的名称。 | 字符串 | 否 | 
| 描述 | 文档的描述。 | 字符串 |  否  | 
| schemaVersion | 文档的架构版本，当前为 1.0。 | 字符串 |  是  | 
| phases | 阶段及其步骤的列表。 |  列表  |  是  | 

阶段的架构定义如下所示。


| 字段 | 描述 | Type | 必需 | 
| --- | --- | --- | --- | 
| name | 阶段的名称。 | 字符串 | 是 | 
| 步骤 | 阶段中的步骤列表。 | 列表  |  是  | 

步骤的架构定义如下所示。


| 字段 | 描述 | Type | 必需 | 默认 值 | 
| --- | --- | --- | --- | --- | 
| name | 用户定义的步骤名称。 | 字符串 |  |  | 
| action | 与运行步骤的模块相关的关键字。 | 字符串 |  |  | 
| timeoutSeconds |  在失败或重试之前，步骤运行的秒数。 此外，支持 -1 值，表示无限超时。不允许 0 和其他负值。  | 整数 |  否  | 7,200 秒（120 分钟） | 
| onFailure |  指定该步骤在失败时应执行的操作。有效值如下所示： [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/imagebuilder/latest/userguide/toe-use-documents.html)  |  字符串  |  否  |  中止 | 
| maxAttempts | 在步骤失败之前允许的最大尝试次数。 | 整数 |  否  | 1 | 
| inputs | 包含操作模块运行步骤所需的参数。 | 字典 |  是  |  | 

## 文档示例
<a name="document-example"></a>

以下示例显示了为目标操作系统执行任务的 AWSTOE 组件文档。

------
#### [ Linux ]

**示例 1：运行自定义二进制文件**  
以下是在 Linux 实例上下载和运行自定义二进制文件的示例文档。

```
name: LinuxBin
description: Download and run a custom Linux binary file.
schemaVersion: 1.0
phases:
  - name: build
    steps:
      - name: Download
        action: S3Download
        inputs:
          - source: s3://<replaceable>amzn-s3-demo-source-bucket</replaceable>/<replaceable>myapplication</replaceable>
            destination: /tmp/<replaceable>myapplication</replaceable>
      - name: Enable
        action: ExecuteBash
        onFailure: Continue
        inputs:
          commands:
            - 'chmod u+x {{ build.Download.inputs[0].destination }}'
      - name: Install
        action: ExecuteBinary
        onFailure: Continue
        inputs:
          path: '{{ build.Download.inputs[0].destination }}'
          arguments:
            - '--install'
      - name: Delete
        action: DeleteFile
        inputs:
          - path: '{{ build.Download.inputs[0].destination }}'
```

------
#### [ Windows ]

**示例 1：安装 Windows 更新**  
以下是一个示例文档，用于安装所有可用的 Windows 更新，运行配置脚本，在创建 AMI 之前验证更改以及在创建 AMI 后测试更改。

```
name: RunConfig_UpdateWindows
description: 'This document will install all available Windows updates and run a config script. It will then validate the changes before an AMI is created. Then after AMI creation, it will test all the changes.'
schemaVersion: 1.0
phases:
  - name: build
    steps:
      - name: DownloadConfigScript
        action: S3Download
        timeoutSeconds: 60
        onFailure: Abort
        maxAttempts: 3
        inputs:
          - source: 's3://customer-bucket/config.ps1'
            destination: 'C:\config.ps1'

      - name: RunConfigScript
        action: ExecutePowerShell
        timeoutSeconds: 120
        onFailure: Abort
        maxAttempts: 3
        inputs:
          file: '{{build.DownloadConfigScript.inputs[0].destination}}'

      - name: Cleanup
        action: DeleteFile
        onFailure: Abort
        maxAttempts: 3
        inputs:
          - path: '{{build.DownloadConfigScript.inputs[0].destination}}'

      - name: RebootAfterConfigApplied
        action: Reboot
        inputs:
          delaySeconds: 60

      - name: InstallWindowsUpdates
        action: UpdateOS

  - name: validate
    steps:
      - name: DownloadTestConfigScript
        action: S3Download
        timeoutSeconds: 60
        onFailure: Abort
        maxAttempts: 3
        inputs:
          - source: 's3://customer-bucket/testConfig.ps1'
            destination: 'C:\testConfig.ps1'

      - name: ValidateConfigScript
        action: ExecutePowerShell
        timeoutSeconds: 120
        onFailure: Abort
        maxAttempts: 3
        inputs:
          file: '{{validate.DownloadTestConfigScript.inputs[0].destination}}'

      - name: Cleanup
        action: DeleteFile
        onFailure: Abort
        maxAttempts: 3
        inputs:
          - path: '{{validate.DownloadTestConfigScript.inputs[0].destination}}'

  - name: test
    steps:
      - name: DownloadTestConfigScript
        action: S3Download
        timeoutSeconds: 60
        onFailure: Abort
        maxAttempts: 3
        inputs:
          - source: 's3://customer-bucket/testConfig.ps1'
            destination: 'C:\testConfig.ps1'

      - name: ValidateConfigScript
        action: ExecutePowerShell
        timeoutSeconds: 120
        onFailure: Abort
        maxAttempts: 3
        inputs:
          file: '{{test.DownloadTestConfigScript.inputs[0].destination}}'
```

**示例 2：在 Windows 实例 AWS CLI 上安装**  
以下是使用安装文件在 Windows 实例 AWS CLI 上安装的示例文档。

```
name: InstallCLISetUp
description: Install &CLI; using the setup file
schemaVersion: 1.0
phases:
  - name: build
    steps:
      - name: Download
        action: S3Download
        inputs:
          - source: s3://aws-cli/AWSCLISetup.exe
            destination: C:\Windows\temp\AWSCLISetup.exe
      - name: Install
        action: ExecuteBinary
        onFailure: Continue
        inputs:
          path: '{{ build.Download.inputs[0].destination }}'
          arguments:
            - '/install'
            - '/quiet'
            - '/norestart'
      - name: Delete
        action: DeleteFile
        inputs:
          - path: '{{ build.Download.inputs[0].destination }}'
```

**示例 3：使用 MSI 安装程序安装 AWS CLI**  
以下是使用 MSI 安装程序安装 AWS CLI 的示例文档。

```
name: InstallCLIMSI
description: Install &CLI; using the MSI installer
schemaVersion: 1.0
phases:
  - name: build
    steps:
      - name: Download
        action: S3Download
        inputs:
          - source: s3://aws-cli/AWSCLI64PY3.msi
            destination: C:\Windows\temp\AWSCLI64PY3.msi
      - name: Install
        action: ExecuteBinary
        onFailure: Continue
        inputs:
          path: 'C:\Windows\System32\msiexec.exe'
          arguments:
            - '/i'
            - '{{ build.Download.inputs[0].destination }}'
            - '/quiet'
            - '/norestart'
      - name: Delete
        action: DeleteFile
        inputs:
          - path: '{{ build.Download.inputs[0].destination }}'
```

------
#### [ macOS ]

**示例 1：运行自定义 macOS 二进制文件**  
以下是在 macOS 实例上下载和运行自定义二进制文件的示例文档。

```
name: macOSBin
description: Download and run a binary file on macOS.
schemaVersion: 1.0
phases:
  - name: build
    steps:
      - name: Download
        action: S3Download
        inputs:
          - source: s3://<replaceable>amzn-s3-demo-source-bucket</replaceable>/<replaceable>myapplication</replaceable>
            destination: /tmp/<replaceable>myapplication</replaceable>
      - name: Enable
        action: ExecuteBash
        onFailure: Continue
        inputs:
          commands:
            - 'chmod u+x {{ build.Download.inputs[0].destination }}'
      - name: Install
        action: ExecuteBinary
        onFailure: Continue
        inputs:
          path: '{{ build.Download.inputs[0].destination }}'
          arguments:
            - '--install'
      - name: Delete
        action: DeleteFile
        inputs:
          - path: '{{ build.Download.inputs[0].destination }}'
```

------