

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

# 使用自訂 AWS TOE 元件的元件文件架構
<a name="toe-use-documents"></a>

若要使用 AWS 任務協調器和執行器 (AWS TOE) 元件架構建置元件，您必須提供 YAML 型文件，代表適用於您建立之元件的階段和步驟。當元件建立新的 Amazon Machine Image (AMI) 或容器映像時 AWS 服務 ，請使用您的元件。

**Topics**
+ [元件文件工作流程](#component-doc-workflow)
+ [元件記錄](#component-logging)
+ [輸入和輸出鏈結](#document-chaining)
+ [文件結構描述和定義](#document-schema)
+ [文件範例](#document-example)
+ [在自訂元件文件中使用變數](toe-user-defined-variables.md)
+ [在 中使用條件式建構 AWS TOE](toe-conditional-constructs.md)
+ [在 AWS TOE 元件文件中使用比較運算子](toe-comparison-operators.md)
+ [在 AWS TOE 元件文件中使用邏輯運算子](toe-logical-operators.md)
+ [在 中使用迴圈建構 AWS TOE](toe-looping-constructs.md)

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

 AWS TOE 元件文件使用階段和步驟來分組相關任務，並將這些任務組織到元件的邏輯工作流程中。

**提示**  
使用 元件建置映像的服務可能會實作有關要用於其建置程序的階段，以及允許執行這些階段的規則。當您設計元件時，請務必考量這一點。

**階段**  
階段代表工作流程在映像建置過程中的進展。例如，Image Builder 服務會在其產生的映像的*建置階段*使用 `build`和 `validate`階段。它在其*測試階段*使用 `test`和 `container-host-test`階段，以確保在建立最終 AMI 或分發容器映像之前，映像快照或容器映像會產生預期的結果。

當元件執行時，每個階段的相關聯命令會按照元件文件中顯示的順序套用。

**階段的規則**
+ 每個階段名稱在文件中必須是唯一的。
+ 您可以在文件中定義多個階段。
+ 您必須在文件中至少包含下列其中一個階段：
  + **build** – 對於映像建置器，此階段通常會在*建置階段*期間使用。
  + **validate** – 對於映像建置器，此階段通常會在*建置階段*期間使用。
  + **測試** – 對於映像建置器，此階段通常會在*測試階段*期間使用。
+ 階段一律會按照文件中定義的順序執行。在 中 AWS CLI 為 AWS TOE 命令指定的順序沒有效果。

**步驟**  
步驟是個別的工作單位，可定義每個階段內的工作流程。步驟會循序執行。不過，一個步驟的輸入或輸出也可以做為輸入饋送至後續步驟。這稱為「鏈結」。

**步驟的規則**
+ 步驟名稱對於 階段必須是唯一的。
+ 步驟必須使用傳回結束代碼的支援動作 （動作模組）。

  如需支援的動作模組的完整清單、運作方式、輸入/輸出值和範例，請參閱 [AWS TOE 元件管理員支援的動作模組](toe-action-modules.md)。

## 元件記錄
<a name="component-logging"></a>

AWS TOE 會在 EC2 執行個體上建立新的日誌資料夾，用於在每次元件執行時建置和測試新映像。對於容器映像，日誌資料夾會存放在容器中。

為了協助在映像建立過程中發生錯誤時進行故障診斷，在執行元件時 AWS TOE 建立的輸入文件和所有輸出檔案都會存放在日誌資料夾中。

日誌資料夾名稱包含下列部分：

1. **日誌目錄** – 當服務執行 AWS TOE 元件時，它會在日誌目錄中傳遞，以及命令的其他設定。針對下列範例，我們會顯示 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** – 這是 AWS TOE 執行一或多個元件時指派的 GUID。

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

AWS TOE 會將下列核心檔案存放在日誌資料夾中：

**輸入檔案**
+ **document.yaml** – 用作命令輸入的文件。元件執行後，此檔案會儲存為成品。

**輸出檔案**
+ **application.log** – 應用程式日誌包含來自 的時間戳記偵錯層級資訊， AWS TOE 了解元件執行時的情況。
+ **detailedoutput.json** – 此 JSON 檔案提供有關執行狀態、輸入、輸出和故障的詳細資訊，適用於元件執行時的所有文件、階段和步驟。
+ **console.log** – 主控台日誌包含元件執行時 AWS TOE 寫入主控台的所有標準輸出 (stdout) 和標準錯誤 (stderr) 資訊。
+ **chaining.json** – 此 JSON 檔案代表 AWS TOE 適用於解析鏈結表達式的最佳化。

**注意**  
日誌資料夾也可能包含此處未涵蓋的其他暫存檔案。

## 輸入和輸出鏈結
<a name="document-chaining"></a>

 AWS TOE 組態管理應用程式以下列格式撰寫參考，提供鏈結輸入和輸出的功能：

`{{ 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 | 文件的名稱。 | String | 否 | 
| description | 文件的描述。 | String |  否  | 
| schemaVersion | 文件的結構描述版本，目前為 1.0。 | String |  是  | 
| 階段 | 階段清單及其步驟。 |  清單  |  是  | 

階段的結構描述定義如下所示。


| 欄位 | 說明 | Type | 必要 | 
| --- | --- | --- | --- | 
| name | 階段的名稱。 | String | 是 | 
| steps | 階段中的步驟清單。 | 清單  |  是  | 

步驟的結構描述定義如下所示。


| 欄位 | 說明 | Type | 必要 | 預設值 | 
| --- | --- | --- | --- | --- | 
| name | 步驟的使用者定義名稱。 | String |  |  | 
| 動作 | 與執行 步驟之模組相關的關鍵字。 | String |  |  | 
| timeoutSeconds |  步驟在失敗或重試前執行的秒數。 此外， 支援 -1 值，表示無限逾時。不允許 0 和其他負值。  | Integer |  否  | 7，200 秒 (120 分鐘） | 
| onFailure |  指定步驟在失敗時應執行的動作。有效值如下： [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_tw/imagebuilder/latest/userguide/toe-use-documents.html)  |  String  |  否  | 中止 | 
| maxAttempts | 在步驟失敗之前允許的嘗試次數上限。 | Integer |  否  | 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： AWS CLI 使用 MSI 安裝程式安裝**  
以下是 AWS CLI 使用 MSI 安裝程式安裝 的範例文件。

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

------

# 在自訂元件文件中使用變數
<a name="toe-user-defined-variables"></a>

變數提供一種方法，以有意義的名稱標記資料，可用於整個應用程式。您可以為複雜工作流程定義具有簡單且可讀取格式的自訂變數，並在 AWS TOE 元件的 YAML 應用程式元件文件中參考它們。

本節提供的資訊可協助您在 YAML 應用程式 AWS TOE 元件文件中定義元件的變數，包括語法、名稱限制條件和範例。

## 常數
<a name="user-defined-vars-constants"></a>

常數是不可變的變數，一旦定義就無法修改或覆寫。您可以使用 AWS TOE 文件 `constants`區段中的值來定義常數。

**常數名稱的規則**
+ 名稱長度必須介於 3 到 128 個字元之間。
+ 名稱只能包含英數字元 (a-z、A-Z、0-9)、破折號 (-) 或底線 (\$1)。
+ 名稱在文件中必須是唯一的。
+ 名稱必須指定為 YAML 字串。

**語法**

```
constants:
  - <name>:
      type: <constant type>
      value: <constant value>
```


| 金鑰名稱 | 必要 | 描述 | 
| --- | --- | --- | 
|  `name`  |  是  | 常數的名稱。文件必須是唯一的 （不得與任何其他參數名稱或常數相同）。 | 
| `value` | 是 | 常數的值。 | 
| `type` | 是 | 常數的類型。支援的類型為 string。 | 

**參考文件中的常數值**  
您可以在 YAML 文件內的步驟或迴圈輸入中參考常數，如下所示：
+ 常數參考區分大小寫，名稱必須完全相符。
+ 名稱必須括在雙大括號 `{{` *MyConstant* 內`}}`。
+ 大括號內允許空格，且會自動修剪。例如，下列所有參考都是有效的：

  `{{ MyConstant }}`, `{{ MyConstant}}`, `{{MyConstant }}`, `{{MyConstant}}`
+ YAML 文件中的參考必須指定為字串 （以單引號或雙引號括住）。

  例如： `- {{ MyConstant }}` 無效，因為它未被識別為字串。

  不過，下列參考皆有效： `- '{{ MyConstant }}'`和 `- "{{ MyConstant }}"`。

**範例**  
步驟輸入中參考的常數

```
name: Download AWS CLI version 2
schemaVersion: 1.0
constants:
  - Source:
      type: string
      value: https://awscli.amazonaws.com/AWSCLIV2.msi
phases:
  - name: build
    steps:
      - name: Download
        action: WebDownload
        inputs:
          - source: '{{ Source }}'
            destination: 'C:\Windows\Temp\AWSCLIV2.msi'
```

迴圈輸入中參考的常數

```
name: PingHosts
schemaVersion: 1.0
constants:
  - Hosts:
      type: string
      value: 127.0.0.1,amazon.com
phases:
  - name: build
    steps:
      - name: Ping
        action: ExecuteBash
        loop:
          forEach:
            list: '{{ Hosts }}'
            delimiter: ','
        inputs:
          commands:
            - ping -c 4 {{ loop.value }}
```

## Parameters
<a name="user-defined-vars-parameters"></a>

參數是可變變數，具有呼叫應用程式可在執行時間提供的設定。您可以在 YAML 文件的 `Parameters`區段中定義參數。

**參數名稱的規則**
+ 名稱長度必須介於 3 到 128 個字元之間。
+ 名稱只能包含英數字元 (a-z、A-Z、0-9)、破折號 (-) 或底線 (\$1)。
+ 名稱在文件中必須是唯一的。
+ 名稱必須指定為 YAML 字串。

### 語法
<a name="vars-parameters-syntax"></a>

```
parameters:
  - <name>:
      type: <parameter type>
      default: <parameter value>
      description: <parameter description>
```


| 金鑰名稱 | 必要 | 描述 | 
| --- | --- | --- | 
| `name` | 是 | 參數名稱。文件必須是唯一的 （不得與任何其他參數名稱或常數相同）。 | 
| `type` | 是 | 參數的資料類型。支援的類型包括：`string`。 | 
| `default` | 否 | 參數的預設值。 | 
| `description` | 否 | 描述 參數。 | 

### 參考文件中的參數值
<a name="vars-parameters-referencing"></a>

您可以在 YAML 文件內的步驟或迴圈輸入中參考參數，如下所示：
+ 參數參考區分大小寫，且名稱必須完全相符。
+ 名稱必須括在雙大括號 `{{` *MyParameter* 內`}}`。
+ 大括號內允許空格，且會自動修剪。例如，下列所有參考都是有效的：

  `{{ MyParameter }}`, `{{ MyParameter}}`, `{{MyParameter }}`, `{{MyParameter}}`
+ YAML 文件中的參考必須指定為字串 （以單引號或雙引號括住）。

  例如： `- {{ MyParameter }}` 無效，因為它未被識別為字串。

  不過，下列參考都有效： `- '{{ MyParameter }}'`和 `- "{{ MyParameter }}"`。

**範例**  
下列範例示範如何在 YAML 文件中使用參數：
+ 請參閱步驟輸入中的參數：

  ```
  name: Download AWS CLI version 2
  schemaVersion: 1.0
  parameters:
    - Source:
        type: string
        default: 'https://awscli.amazonaws.com/AWSCLIV2.msi'
        description: The AWS CLI installer source URL.
  phases:
    - name: build
      steps:
        - name: Download
          action: WebDownload
          inputs:
            - source: '{{ Source }}'
              destination: 'C:\Windows\Temp\AWSCLIV2.msi'
  ```
+ 請參閱迴圈輸入中的參數：

  ```
  name: PingHosts
  schemaVersion: 1.0
  parameters:
    - Hosts:
        type: string
        default: 127.0.0.1,amazon.com
        description: A comma separated list of hosts to ping.
  phases:
    - name: build
      steps:
        - name: Ping
          action: ExecuteBash
          loop:
            forEach:
              list: '{{ Hosts }}'
              delimiter: ','
          inputs:
            commands:
              - ping -c 4 {{ loop.value }}
  ```

### 在執行時間覆寫參數
<a name="vars-parameters-set-at-runtime"></a>

您可以從 AWS CLI 搭配索引鍵/值對使用 `--parameters`選項，在執行時間設定參數值。
+ 將參數鍵/值對指定為名稱和值，並以等號 (<name>=<value>) 分隔。
+ 多個參數必須以逗號分隔。
+ 在 YAML 元件文件中找不到的參數名稱會被忽略。
+ 參數名稱和值都是必要的。

**重要**  
元件參數是純文字值，並會登入 AWS CloudTrail。建議您使用 AWS Secrets Manager 或 AWS Systems Manager 參數存放區來存放秘密。如需 Secrets Manager 的詳細資訊，請參閱*AWS Secrets Manager 《 使用者指南*》中的[什麼是 Secrets Manager？](https://docs.aws.amazon.com/secretsmanager/latest/userguide/intro.html)。如需 AWS Systems Manager 參數存放區的詳細資訊，請參閱*AWS Systems Manager 《 使用者指南*》中的[AWS Systems Manager 參數存放區](https://docs.aws.amazon.com/systems-manager/latest/userguide/systems-manager-parameter-store.html)。

#### 語法
<a name="vars-runtime-parameters-syntax"></a>

```
--parameters name1=value1,name2=value2...
```


| CLI 選項 | 必要 | Description | 
| --- | --- | --- | 
| --parameters *name*=*value*，... | 否 | 此選項會取得索引鍵/值對的清單，並將參數名稱做為索引鍵。 | 

**範例**  
下列範例示範如何在 YAML 文件中使用參數：
+ `--parameter` 此選項中指定的參數鍵/值對無效：

  ```
  --parameters ntp-server=
  ```
+ 使用 中的 `--parameter`選項設定一個參數鍵/值對 AWS CLI：

  ```
  --parameters ntp-server=ntp-server-windows-qe.us-east1.amazon.com
  ```
+ 使用 中的 `--parameter`選項設定多個參數鍵值對 AWS CLI：

  ```
  --parameters ntp-server=ntp-server.amazon.com,http-url=https://internal-us-east1.amazon.com
  ```

## 使用 Systems Manager 參數存放區參數
<a name="toe-ssm-parameters"></a>

您可以在元件文件中參考 AWS Systems Manager 參數存放區參數 (SSM 參數），方法是使用 為變數加上字首`aws:ssm`。例如 

`{{ aws:ssm:/my/param }}` 解析為 SSM 參數 的值`/my/param`。

此功能支援下列 SSM 參數類型：
+ 字串 – 對應至 AWS TOE 字串類型。
+ StringList – 映射至 AWS TOE `stringList`類型。
+ SecureString – 對應至 AWS TOE 字串類型。

如需參數存放區的詳細資訊，請參閱*AWS Systems Manager 《 使用者指南*》中的[AWS Systems Manager 參數存放](https://docs.aws.amazon.com/systems-manager/latest/userguide/systems-manager-parameter-store.html)區。

您也可以使用 SSM 參數 來參考 AWS Secrets Manager 秘密`SecureString`。例如：`{{ aws:ssm:/aws/reference/secretsmanager/test/test-secret }}`。如需詳細資訊，請參閱[參考 AWS Secrets Manager 參數存放區參數中的秘密](https://docs.aws.amazon.com/systems-manager/latest/userguide/integration-ps-secretsmanager.html)。

**重要**  
Image Builder 從其日誌中排除`SecureString`參數解析。不過，您也必須負責確保不會透過元件文件中發出的命令記錄敏感資訊。例如，如果您使用 `echo`命令搭配安全字串，命令會將純文字值寫入日誌。

### 所需的 IAM 許可
<a name="toe-ssm-parameters-permissions"></a>

若要在元件中使用 Systems Manager 參數，您的執行個體角色必須具有參數資源 ARN 的`ssm:GetParameter`許可。例如：

------
#### [ JSON ]

****  

```
{
	"Version":"2012-10-17",		 	 	 
	"Statement": [
		{
			"Effect": "Allow",
			"Action": "ssm:GetParameter",
			"Resource": "arn:aws:ssm:*:111122223333:parameter/ImageBuilder-*"
		}
	]
}
```

------

若要存取加密的值，您也需要下列許可：
+ `kms:Decrypt` 針對使用客戶受管加密的`SecureString`參數或 AWS Secrets Manager 值新增 AWS KMS key。
+ `secretsmanager:GetSecretValue` 如果您參考 Secrets Manager 秘密，請新增 。

### 參考元件文件中的 SSM 參數
<a name="toe-ssm-parameters-example"></a>

下列範例示範如何在元件中參考 Systems Manager 參數的 Systems Manager 參數存放區參數：

```
name: UseSSMParameterVariable
description: This is a sample component document that prints out the value of an SSM Parameter. Never do this for a SecureString parameter.
schemaVersion: 1.0

phases:
  - name: verify
    steps:
      - name: EchoParameterValue
        action: ExecuteBash
        inputs:
          commands:
            - echo "Log SSM parameter name: /my/test/param, value {{ aws:ssm:/my/test/param }}."
```

### SSM 參數的動態執行期變數解析
<a name="toe-dynamic-vars"></a>

AWSTOE 提供下列內建函數，您可以在變數參考內操作或轉換執行時間的值。

#### 解析函數
<a name="toe-function-resolve"></a>

`resolve` 函數會在另一個變數參考內解析變數參考，允許動態變數名稱參考。這在使用 SSM 參數時非常有用，其中部分參數路徑可能是可變的，並以文件參數的形式傳入。

`resolve` 函數僅支援 SSM 參數名稱部分的動態解析。

##### 語法
<a name="toe-function-resolve-syntax"></a>

`dynamic_variable` 下列範例中的 代表 SSM 參數的名稱，且必須是下列其中一項：
+ SSM 參數參考 （例如 `aws:ssm:/my/param`)
+ 元件文件參數參考 （例如 `parameter-name`)

```
{{ aws:ssm:resolve(dynamic_variable) }}
```

##### 範例：在執行時間解析 SSM 參數
<a name="toe-function-resolve-examples"></a>

下列範例示範如何在 YAML 元件文件中使用 `resolve`函數：

```
name: SsmParameterTest
description: This component verifies an SSM parameter variable reference with the echo command.
schemaVersion: 1.0

parameters:
  - parameter-name:
      type: string
      description: "test"

phases:
  - name: validate
    steps:
      - name: PrintDynamicVariable
        action: ExecuteBash
        inputs:
          commands:
            - echo "{{ aws:ssm:resolve(parameter-name) }}"
```

# 在 中使用條件式建構 AWS TOE
<a name="toe-conditional-constructs"></a>

條件式建構會根據指定的條件式表達式評估為 `true`或 ，在元件文件中執行不同的動作`false`。您可以使用 `if` 建構來控制元件文件中的執行流程。

## 如果建構
<a name="toe-conditional-if"></a>

您可以使用 `if` 建構來評估步驟是否應該執行。根據預設，當`if`條件式表達式評估為 `true`、 AWS TOE 執行 步驟，以及當條件評估為 時`false`， 會 AWS TOE 略過 步驟。如果略過步驟，則當 評估階段和文件是否成功執行時 AWS TOE ，會將其視為成功步驟。

**注意**  
即使步驟觸發重新啟動， `if`陳述式只會評估一次。如果步驟重新啟動，則會辨識該`if`陳述式已進行評估，並繼續離開的位置。

### 語法
<a name="toe-conditional-if-syntax"></a>

```
if:
  - <conditional expression>:
      [then: <step action>]
      [else: <step action>]
```


| 金鑰名稱 | 必要 | Description | 
| --- | --- | --- | 
| 條件式表達式 | 是 |  條件式表達式在最上層可以包含以下其中一種類型的運算子。 [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_tw/imagebuilder/latest/userguide/toe-conditional-constructs.html) 如果您的表達式必須符合多個條件，請使用邏輯運算子來指定您的條件。  | 
| then | 否 |  定義條件式表達式評估為 時要採取的動作`true`。  | 
| else | 否 |  定義條件式表達式評估為 時要採取的動作`false`。  | 
| 步驟動作 | 有條件 |  使用 `then`或 時`else`，您必須指定下列其中一個步驟動作： [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_tw/imagebuilder/latest/userguide/toe-conditional-constructs.html)  | 

**範例 1：安裝套件**  
 AWS TOE 元件文件中的下列範例步驟使用邏輯運算子來測試參數值，並在套件解壓縮時執行適當的套件管理員命令來安裝應用程式。

```
    - name: InstallUnzipAptGet
      action: ExecuteBash
      if:
        and:
            - binaryExists: 'apt-get'
            - not:
                binaryExists: 'unzip'
      inputs:
        commands:
            - sudo apt-get update
            - sudo apt-get install -y unzip

    - name: InstallUnzipYum
      action: ExecuteBash
      if:
        and:
            - binaryExists: 'yum'
            - not:
                binaryExists: 'unzip'
      inputs:
        commands:
            - sudo yum install -y unzip

    - name: InstallUnzipZypper
      action: ExecuteBash
      if:
        and:
            - binaryExists: 'zypper'
            - not:
                binaryExists: 'unzip'
      inputs:
        commands:
            - sudo zypper refresh
            - sudo zypper install -y unzip
```

**範例 2：略過步驟**  
下列範例顯示略過步驟的兩種方式。一個使用邏輯運算子，另一個使用具有`Skip`步驟動作的比較運算子。

```
# Creates a file if it does not exist using not
- name: CreateMyConfigFile-1
  action: ExecuteBash
  if:
    not:
      fileExists: '/etc/my_config'
  inputs:
    commands:
      - echo "Hello world" > '/etc/my_config'

# Creates a file if it does not exist using then and else
- name: CreateMyConfigFile-2
  action: ExecuteBash
  if:
    fileExists: '/etc/my_config'
    then: Skip
    else: Execute
  inputs:
    commands:
      - echo "Hello world" > '/etc/my_config'
```

# 在 AWS TOE 元件文件中使用比較運算子
<a name="toe-comparison-operators"></a>

您可以搭配 **[聲明](toe-action-modules.md#action-modules-assertion)**動作模組和使用 的條件式表達式使用下列比較運算子[如果建構語法](toe-conditional-constructs.md#toe-conditional-if)。比較運算子可以在單一值上操作，例如 `stringIsEmpty`，也可以比較基準值與第二個值 （變數值），以判斷條件式表達式是否評估為 `true`或 `false`。

如果比較操作於兩個值，則第二個值可以是鏈結變數。

比較不同類型的值時，下列值轉換可能會在比較之前發生：
+ 對於數值比較，如果變數值是字串， 會在評估之前將字串 AWS TOE 轉換為數字。如果無法轉換，比較會傳回 `false`。例如，如果變數值為 `"1.0"`，則轉換會運作，但如果變數值為轉換`"a10"`會失敗。
+ 對於字串比較，如果變數值是數字， 會在評估之前將其 AWS TOE 轉換為字串。

## 比較字串
<a name="toe-compare-strings"></a>

下列比較運算子使用字串來比較值、測試空格或空字串，或比較輸入值與規則運算式模式。字串比較不區分大小寫，而且不會從字串輸入的開頭或結尾修剪空格。

**字串比較運算子**
+ [stringIsEmpty](#stringIsEmpty)
+ [stringIsWhitespace](#stringIsWhitespace)
+ [stringEquals](#stringEquals)
+ [stringLessThan](#stringLessThan)
+ [stringLessThanEquals](#stringLessThanEquals)
+ [stringGreaterThan](#stringGreaterThan)
+ [stringGreaterThanEquals](#stringGreaterThanEquals)
+ [patternMatches](#patternMatches)

**stringIsEmpty**  
`true` 如果指定的字串不包含任何字元，運算`stringIsEmpty`子會傳回 。例如：  

```
# Evaluates to true
stringIsEmpty: ""

# Evaluates to false
stringIsEmpty: " "
				
# Evaluates to false
stringIsEmpty: "Hello."
```

**stringIsWhitespace**  
測試 指定的字串是否只`stringIsWhitespace`包含空格。例如：  

```
# Evaluates to true
stringIsWhitespace: "   "

# Evaluates to false
stringIsWhitespace: ""
				
# Evaluates to false
stringIsWhitespace: " Hello?"
```

**stringEquals**  
測試 指定的字串`stringEquals`是否與 `value` 參數中指定的字串完全相符。例如：  

```
# Evaluates to true
stringEquals: 'Testing, testing...'
value: 'Testing, testing...'

# Evaluates to false
stringEquals: 'Testing, testing...'
value: 'Hello again.'

# Evaluates to false
stringEquals: 'Testing, testing...'
value: 'TESTING, TESTING....'

# Evaluates to false
stringEquals: 'Testing, testing...'
value: '   Testing, testing...'
				
# Evaluates to false
stringEquals: 'Testing, testing...'
value: 'Testing, testing...   '
```

**stringLessThan**  
測試 指定的字串是否`stringLessThan`小於 `value` 參數中指定的字串。例如：  

```
# Evaluates to true
# This comparison operator isn't case sensitive
stringlessThan: 'A'
value: 'a'

# Evaluates to true - 'a' is less than 'b'
stringlessThan: 'b'
value: 'a'

# Evaluates to true
# Numeric strings compare as less than alphabetic strings
stringlessThan: 'a'
value: '0'

# Evaluates to false
stringlessThan: '0'
value: 'a'
```

**stringLessThanEquals**  
測試為 指定的字串是否`stringLessThanEquals`小於或等於 `value` 參數中指定的字串。例如：  

```
# Evaluates to true - 'a' is equal to 'a'
stringLessThanEquals: 'a'
value: 'a'

# Evaluates to true - since the comparison isn't case sensitive, 'a' is equal to 'A'
stringLessThanEquals: 'A'
value: 'a'

# Evaluates to true - 'a' is less than 'b'
stringLessThanEquals: 'b'
value: 'a'

# Evaluates to true - '0' is less than 'a'
stringLessThanEquals: 'a'
value: '0'

# Evaluates to false - 'a' is greater than '0'
stringLessThanEquals: '0'
value: 'a'
```

**stringGreaterThan**  
測試 指定的字串是否`stringGreaterThan`大於 `value` 參數中指定的字串。例如：  

```
# Evaluates to false - since the comparison isn't case sensitive, 'A' is equal to 'a'
stringGreaterThan: 'a'
value: 'A'

# Evaluates to true - 'b' is greater than 'a'
stringGreaterThan: 'a'
value: 'b'

# Evaluates to true - 'a' is greater than '0'
stringGreaterThan: '0'
value: 'a'

# Evaluates to false - '0' is less than 'a'
stringGreaterThan: 'a'
value: '0'
```

**stringGreaterThanEquals**  
測試為 指定的字串是否`stringGreaterThanEquals`大於或等於 `value` 參數中指定的字串。例如：  

```
# Evaluates to true - 'a' is equal to 'A'
stringGreaterThanEquals: 'A'
value: 'a'

# Evaluates to true - 'b' is greater than 'a'
stringGreaterThanEquals: 'a'
value: 'b'

# Evaluates to true - 'a' is greater than '0'
stringGreaterThanEquals: '0'
value: 'a'

# Evaluates to false - '0' is less than 'a'
stringGreaterThanEquals: 'a'
value: '0'
```

**patternMatches**  
測試 `value` 參數中指定的字串是否符合為 指定的 regex 模式`patternMatches`。比較使用符合 RE2 語法的 [Golang regexp 套件](https://pkg.go.dev/regexp)。如需 RE2 規則的詳細資訊，請參閱 *GitHub* [中的 Google/re2](https://github.com/google/re2/wiki/Syntax) 儲存庫。  
下列範例顯示傳回 的模式比對`true`：  

```
patternMatches: '^[a-z]+$'
value: 'ThisIsValue'
```

## 比較數字
<a name="toe-compare-numbers"></a>

下列比較運算子使用數字。根據 YAML 規格，這些運算子提供的值必須是下列其中一種類型。對數值比較的支援使用 golang 大型套件比較運算子，例如：[func (\$1Float) Cmp](https://pkg.go.dev/math/big#Float.Cmp)。
+ Integer
+ 浮點數 （以 float64 為基礎，支援從 -1.7e\$1308 到 \$11.7e\$1308 的數字）
+ 符合下列 regex 模式的字串： `^[-+]?([0-9]+[.])?[0-9]+$`

**數字比較運算子**
+ [numberEquals](#numberEquals)
+ [numberLessThan](#numberLessThan)
+ [numberLessThanEquals](#numberLessThanEquals)
+ [numberGreaterThan](#numberGreaterThan)
+ [numberGreaterThanEquals](#numberGreaterThanEquals)

**numberEquals**  
測試 指定的數字是否`numberEquals`等於 `value` 參數中指定的數字。下列所有範例比較都會傳回 `true`：  

```
# Values provided as a positive number
numberEquals: 1
value: 1

# Comparison value provided as a string
numberEquals: '1'
value: 1

# Value provided as a string
numberEquals: 1
value: '1'

# Values provided as floats
numberEquals: 5.0
value: 5.0

# Values provided as a negative number
numberEquals: -1
value: -1
```

**numberLessThan**  
測試 指定的數字是否`numberLessThan`小於 `value` 參數中指定的數字。例如：  

```
# Evaluates to true
numberLessThan: 2
value: 1

# Evaluates to true
numberLessThan: 2
value: 1.9

# Evaluates to false
numberLessThan: 2
value: '2'
```

**numberLessThanEquals**  
測試 指定的數字是否`numberLessThanEquals`小於或等於 `value` 參數中指定的數字。例如：  

```
# Evaluates to true
numberLessThanEquals: 2
value: 1

# Evaluates to true
numberLessThanEquals: 2
value: 1.9

# Evaluates to true
numberLessThanEquals: 2
value: '2'

# Evaluates to false
numberLessThanEquals: 2
value: 2.1
```

**numberGreaterThan**  
測試 指定的數字是否`numberGreaterThan`大於 `value` 參數中指定的數字。例如：  

```
# Evaluates to true
numberGreaterThan: 1
value: 2

# Evaluates to true
numberGreaterThan: 1
value: 1.1

# Evaluates to false
numberGreaterThan: 1
value: '1'
```

**numberGreaterThanEquals**  
測試 指定的數字是否`numberGreaterThanEquals`大於或等於 `value` 參數中指定的數字。例如：  

```
# Evaluates to true
numberGreaterThanEquals: 1
value: 2

# Evaluates to true
numberGreaterThanEquals: 1
value: 1.1

# Evaluates to true
numberGreaterThanEquals: 1
value: '1'

# Evaluates to false
numberGreaterThanEquals: 1
value: 0.8
```

## 檢查檔案
<a name="toe-check-files"></a>

下列比較運算子會檢查檔案雜湊，或檢查檔案或資料夾是否存在。

**檔案和資料夾運算子**
+ [binaryExists](#binaryExists)
+ [fileExists](#fileExists)
+ [folderExists](#folderExists)
+ [fileMD5Equals](#fileMD5Equals)
+ [fileSHA1Equals](#fileSHA1Equals)
+ [fileSHA256Equals](#fileSHA256Equals)
+ [fileSHA512Equals](#fileSHA512Equals)

**binaryExists**  
測試應用程式是否可在目前路徑中使用。例如：  

```
binaryExists: 'foo'
```
在 Linux 和 macOS 系統上，對於名為 *foo* 的應用程式，其運作方式與下列 bash 命令相同：**type *foo* >/dev/null 2>&1**，其中 **\$1? == 0**表示成功比較。  
在 Windows 系統上，對於名為 *foo* 的應用程式，這的運作方式與 PowerShell 命令相同**& C:\$1Windows\$1System32\$1where.exe /Q *foo***，其中 **\$1LASTEXITCODE = 0**表示成功比較。

**fileExists**  
測試檔案是否存在於指定的路徑。您可以提供絕對或相對路徑。如果您指定的位置存在且為 檔案，則比較會評估為 `true`。例如：  

```
fileExists: '/path/to/file'
```
在 Linux 和 macOS 系統上，這的運作方式與下列 bash 命令相同：**-d */path/to/file***，其中 **\$1? == 0**表示成功比較。  
在 Windows 系統上，這的運作方式與 PowerShell 命令 相同**Test-Path -Path '*C:\$1path\$1to\$1file*' -PathType 'Leaf'**。

**folderExists**  
測試資料夾是否存在於指定的路徑。您可以提供絕對或相對路徑。如果您指定的位置存在且 是資料夾，則比較會評估為 `true`。例如：  

```
folderExists: '/path/to/folder'
```
在 Linux 和 macOS 系統上，這的運作方式與下列 bash 命令相同：**-d */path/to/folder***，其中 **\$1? == 0**表示成功比較。  
在 Windows 系統上，這的運作方式與 PowerShell 命令 相同**Test-Path -Path '*C:\$1path\$1to\$1folder*' -PathType 'Container'**。

**fileMD5Equals**  
測試檔案的 MD5 雜湊是否等於指定的值。例如：  

```
fileMD5Equals: '<MD5Hash>'
path: '/path/to/file'
```

**fileSHA1Equals**  
測試檔案的 SHA1 雜湊是否等於指定的值。例如：  

```
fileSHA1Equals: '<SHA1Hash>'
path: '/path/to/file'
```

**fileSHA256Equals**  
測試檔案的 SHA256 雜湊是否等於指定的值。例如：  

```
fileSHA256Equals: '<SHA256Hash>'
path: '/path/to/file'
```

**fileSHA512Equals**  
測試檔案的 SHA512 雜湊是否等於指定的值。例如：  

```
fileSHA512Equals: '<SHA512Hash>'
path: '/path/to/file'
```

# 在 AWS TOE 元件文件中使用邏輯運算子
<a name="toe-logical-operators"></a>

您可以使用下列邏輯運算子來新增或修改元件文件中的條件式表達式。 會依條件的指定順序 AWS TOE 評估條件式表達式。如需元件文件比較運算子的詳細資訊，請參閱 [在 AWS TOE 元件文件中使用比較運算子](toe-comparison-operators.md)。

**而且**  
使用 `and`運算子，您可以將兩個或多個比較評估為單一表達式。當清單中的所有條件都是 true `true`時，表達式會評估為 。否則，表達式會評估為 `false`。  
**範例：**  
下列範例會執行兩個比較：字串和數字。這兩個比較都是 true，因此表達式會評估為 true。

```
and:
  - stringEquals: 'test_string'
    value: 'test_string'
  - numberEquals: 1
    value: 1
```
下列範例也會執行兩個比較。第一個比較是 false，此時評估會停止並略過第二個比較。表達式會評估為 `false`。  

```
and:
  - stringEquals: 'test_string'
    value: 'Hello world!'
  - numberEquals: 1
    value: 1
```

**或**  
使用 `or`運算子，您可以將兩個或多個比較評估為單一表達式。當其中一個指定的比較為 true `true`時，表達式會評估為 。如果沒有指定的比較評估為 `true`，則表達式評估為 `false`。  
**範例：**  
下列範例會執行兩個比較：字串和數字。第一個比較是 true，因此表達式會評估為 `true`，並略過第二個比較。

```
or:
  - stringEquals: 'test_string'
    value: 'test_string'
  - numberEquals: 1
    value: 3
```
下列範例也會執行兩個比較。第一個比較是 false，評估會繼續進行。第二個比較是 true，因此表達式會評估為 `true`。  

```
or:
  - stringEquals: 'test_string'
    value: 'Hello world!'
  - numberEquals: 1
    value: 1
```
在最後一個範例中，兩個比較都是 false，因此表達式會評估為 `false`。  

```
or:
  - stringEquals: 'test_string'
    value: 'Hello world!'
  - numberEquals: 1
    value: 3
```

**不是**  
使用 `not`運算子，您可以否定單一比較。如果比較為 false`true`，表達式會評估為 。如果比較為 true，則表達式會評估為 `false`。  
**範例：**  
下列範例會執行字串比較。比較為 false，因此表達式會評估為 `true`。

```
not:
  - stringEquals: 'test_string'
    value: 'Hello world!'
```
下列範例也會執行字串比較。比較是 true，因此表達式會評估為 `false`。  

```
not:
  - stringEquals: 'test_string'
    value: 'test_string'
```

# 在 中使用迴圈建構 AWS TOE
<a name="toe-looping-constructs"></a>

本節提供的資訊可協助您在 中建立迴圈建構 AWS TOE。循環建構定義一系列重複的指示。您可以在 中使用下列類型的循環建構 AWS TOE：
+ `for` 建構 – 反覆運算整數的邊界序列。
+ `forEach` 建構
  + `forEach` 具有輸入清單的迴圈 – 反覆運算字串的有限集合。
  + `forEach` 使用分隔清單的迴圈 – 反覆運算由分隔符號聯結的有限字串集合。

**注意**  
迴圈建構模組僅支援字串資料類型。

**Topics**
+ [參考反覆運算變數](#toe-loop-iteration-variables)
+ [迴圈建構的類型](#toe-loop-types)
+ [步驟欄位](#toe-loop-step-fields)
+ [步驟和反覆運算輸出](#toe-loop-step-output)

## 參考反覆運算變數
<a name="toe-loop-iteration-variables"></a>

若要參考目前反覆運算變數的索引和值，`{{ loop.* }}`必須在包含循環建構的步驟輸入內使用參考表達式。此表達式無法用來參考另一個步驟的迴圈建構的反覆運算變數。

參考表達式包含下列成員：
+ `{{ loop.index }}` – 目前反覆運算的順序位置，其索引為 `0`。
+ `{{ loop.value }}` – 與目前反覆運算變數相關聯的值。

### 迴圈名稱
<a name="toe-loop-iteration-variables-names"></a>

 所有循環建構都有用於識別的選用名稱欄位。如果提供迴圈名稱，則可用來參考步驟輸入內文中的反覆運算變數。若要參考具名迴圈的反覆運算索引和值，請在步驟的輸入內文`{{ loop.* }}`中使用 `{{ <loop_name>.* }}` 搭配 。此表達式無法用來參考另一個步驟的具名迴圈建構。

參考表達式包含下列成員：
+ `{{ <loop_name>.index }}` – 具名迴圈目前反覆運算的順序位置，其索引為 `0`。
+ `{{ <loop_name>.value }}` – 與具名迴圈的目前反覆運算變數相關聯的值。

### 解決參考表達式
<a name="toe-loop-iteration-variables-expressions"></a>

會 AWS TOE 解析參考表達式，如下所示：
+ `{{ <loop_name>.* }}` –使用以下邏輯 AWS TOE 解決此表達式：
  + 如果目前執行步驟的迴圈符合 `<loop_name>`值，則參考表達式會解析為目前執行步驟的迴圈建構。
  + `<loop_name>` 如果在目前執行的步驟中出現， 會解析為具名迴圈建構。
+ `{{ loop.* }}` –使用目前執行步驟中定義的迴圈建構來 AWS TOE 解析表達式。

如果在不包含迴圈的步驟中使用參考表達式，則 AWS TOE 不會解析表達式，並且它們會出現在步驟中，而不會替換。

**注意**  
參考表達式必須以雙引號括住，以便 YAML 編譯器正確解譯。

## 迴圈建構的類型
<a name="toe-loop-types"></a>

本節提供有關迴圈可在 中使用的建構類型的資訊和範例 AWS TOE。

**Topics**
+ [`for` 迴圈](#toe-loop-types-for)
+ [`forEach` 具有輸入清單的迴圈](#toe-loop-types-foreach)
+ [`forEach` 具有分隔清單的迴圈](#toe-loop-types-foreach-delimited)

### `for` 迴圈
<a name="toe-loop-types-for"></a>

`for` 迴圈會在變數開始和結束所概述的邊界內指定的整數範圍上反覆運算。反覆運算值位於集合中`[start, end]`，並包含邊界值。

AWS TOE 驗證 `start`、 `end`和 `updateBy`值，以確保組合不會造成無限迴圈。

`for` 迴圈結構描述

```
  - name: "StepName"
    action: "ActionModule"
    loop:
      name: "string"
      for:
        start: int
        end: int
        updateBy: int
inputs:
  ...
```


**`for` 迴圈輸入**  

| 欄位 | 說明 | Type | 必要 | 預設 | 
| --- | --- | --- | --- | --- | 
|  `name`  | 迴圈的唯一名稱。與相同階段中的其他迴圈名稱相比，它必須是唯一的。 |  String  |  否  |  ""  | 
|  `start`  | 反覆運算的起始值。不接受鏈結表達式。 |  Integer  |  是  |  N/A  | 
| `end` | 反覆運算的結束值。不接受鏈結表達式。 | Integer | 是 | N/A | 
| `updateBy` | 透過新增更新反覆運算值的差異。它必須是負值或非零值。不接受鏈結表達式。 | Integer | 是 | N/A | 

`for` 迴圈輸入範例

```
  - name: "CalculateFileUploadLatencies"
    action: "ExecutePowerShell"
    loop:
      for:
        start: 100000
        end: 1000000
        updateBy: 100000
    inputs:
      commands:
        - |
          $f = new-object System.IO.FileStream c:\temp\test{{ loop.index }}.txt, Create, ReadWrite
          $f.SetLength({{ loop.value }}MB)
          $f.Close()
        - c:\users\administrator\downloads\latencyTest.exe --file c:\temp\test{{ loop.index }}.txt
        - AWS s3 cp c:\users\administrator\downloads\latencyMetrics.json s3://bucket/latencyMetrics.json
        - |
          Remove-Item -Path c:\temp\test{{ loop.index }}.txt
          Remove-Item -Path c:\users\administrator\downloads\latencyMetrics.json
```

### `forEach` 具有輸入清單的迴圈
<a name="toe-loop-types-foreach"></a>

`forEach` 迴圈會在明確值清單上反覆運算，可以是字串和鏈結表達式。

`forEach` 具有輸入清單結構描述的迴圈

```
  - name: "StepName"
    action: "ActionModule"
    loop:
      name: "string"
      forEach:
        - "string"
    inputs:
  ...
```


**`forEach` 具有輸入清單輸入的迴圈**  

| 欄位 | 說明 | Type | 必要 | 預設 | 
| --- | --- | --- | --- | --- | 
|  `name`  | 迴圈的唯一名稱。與相同階段中的其他迴圈名稱相比，它必須是唯一的。 |  String  |  否  |  ""  | 
|  `forEach` 迴圈字串清單  |  反覆運算的字串清單。接受鏈結表達式做為清單中的字串。鏈結表達式必須以雙引號括住，YAML 編譯器才能正確解譯。  |  字串清單  |  是  |  N/A  | 

`forEach` 具有輸入清單的迴圈範例 1

```
  - name: "ExecuteCustomScripts"
    action: "ExecuteBash"
    loop:
      name: BatchExecLoop
      forEach:
        - /tmp/script1.sh
        - /tmp/script2.sh
        - /tmp/script3.sh
    inputs:
      commands:
        - echo "Count {{ BatchExecLoop.index }}"
        - sh "{{ loop.value }}"
        - |
          retVal=$?
          if [ $retVal -ne 0 ]; then
            echo "Failed"
          else
            echo "Passed"
         fi
```

`forEach` 具有輸入清單的迴圈範例 2

```
  - name: "RunMSIWithDifferentArgs"
    action: "ExecuteBinary"
    loop:
      name: MultiArgLoop
      forEach:
        - "ARG1=C:\Users ARG2=1"
        - "ARG1=C:\Users"
        - "ARG1=C:\Users ARG3=C:\Users\Administrator\Documents\f1.txt"
    inputs:
      commands:
        path: "c:\users\administrator\downloads\runner.exe"
        args:
          - "{{ MultiArgLoop.value }}"
```

`forEach` 具有輸入清單的迴圈範例 3

```
  - name: "DownloadAllBinaries"
    action: "S3Download"
    loop:
      name: MultiArgLoop
      forEach:
        - "bin1.exe"
        - "bin10.exe"
        - "bin5.exe"
    inputs:
      - source: "s3://bucket/{{ loop.value }}"
        destination: "c:\temp\{{ loop.value }}"
```

### `forEach` 具有分隔清單的迴圈
<a name="toe-loop-types-foreach-delimited"></a>

迴圈會反覆運算字串，其中包含以分隔符號分隔的值。若要反覆運算字串的元件， AWS TOE 請使用分隔符號將字串分割為適合反覆運算的陣列。

`forEach` 具有分隔清單結構描述的迴圈

```
  - name: "StepName"
    action: "ActionModule"
    loop:
      name: "string"
      forEach:
        list: "string"
        delimiter: ".,;:\n\t -_"
    inputs:
  ...
```


**`forEach` 具有分隔清單輸入的迴圈**  

| 欄位 | 說明 | Type | 必要 | 預設 | 
| --- | --- | --- | --- | --- | 
|  `name`  | 提供給迴圈的唯一名稱。與相同階段中的其他迴圈名稱相比，它應該是唯一的。 |  String  |  否  |  ""  | 
|  `list`  | 由共同分隔符號字元聯結的組成字串組成的字串。也接受鏈結表達式。如果是鏈結表達式，請確保以雙引號括住這些表達式，以便 YAML 編譯器正確解譯。 | String |  是  |  N/A  | 
| `delimiter` | 用來分隔區塊中字串的字元。預設為逗號字元。指定清單中只允許一個分隔符號字元：[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_tw/imagebuilder/latest/userguide/toe-looping-constructs.html) 無法使用鏈結表達式。 | String | 否 | 逗號： "," | 

**注意**  
的值`list`視為不可變字串。如果在執行時間`list`變更 的來源，則不會在執行期間反映。

`forEach` 使用分隔清單的迴圈範例 1

此範例使用下列鏈結表達式模式來參考另一個步驟的輸出：`<phase_name>.<step_name>.[inputs | outputs].<var_name>`。

```
  - name: "RunMSIs"
    action: "ExecuteBinary"
    loop:
      forEach:
        list: "{{ build.GetAllMSIPathsForInstallation.outputs.stdout }}"
        delimiter: "\n"
    inputs:
      commands:
        path: "{{ loop.value }}"
```

`forEach` 使用分隔清單的迴圈範例 2

```
  - name: "UploadMetricFiles"
    action: "S3Upload"
    loop:
      forEach:
        list: "/tmp/m1.txt,/tmp/m2.txt,/tmp/m3.txt,..."
    inputs:
      commands:
        - source: "{{ loop.value }}"
          destination: "s3://bucket/key/{{ loop.value }}"
```

## 步驟欄位
<a name="toe-loop-step-fields"></a>

迴圈是步驟的一部分。任何與執行步驟相關的欄位都不會套用至個別反覆運算。步驟欄位僅適用於步驟層級，如下所示：
+ *timeoutSeconds* – 迴圈的所有反覆運算必須在此欄位指定的期間內執行。如果迴圈執行逾時，則 會 AWS TOE 執行步驟的重試政策，並重設每次新嘗試的逾時參數。如果迴圈執行在達到重試次數上限後超過逾時值，步驟的失敗訊息會指出迴圈執行已逾時。
+ *onFailure* – 失敗處理會套用至步驟，如下所示：
  + 如果 *onFailure* 設定為 `Abort`，則會 AWS TOE 退出迴圈，並根據重試政策重試步驟。在重試嘗試次數上限之後， 會將目前步驟 AWS TOE 標記為失敗，並停止執行程序。

    AWS TOE 會將父階段的狀態碼和文件設定為 `Failed`。
**注意**  
在失敗的步驟之後，不會執行任何進一步的步驟。
  + 如果 *onFailure* 設定為 `Continue`， AWS TOE 會結束迴圈，並根據重試政策重試步驟。在重試嘗試次數上限之後， 會將目前步驟 AWS TOE 標記為失敗，並繼續執行下一個步驟。

    AWS TOE 會將父階段的狀態碼和文件設定為 `Failed`。
  + 如果 *onFailure* 設定為 `Ignore`， AWS TOE 會結束迴圈，並根據重試政策重試步驟。在重試嘗試次數上限之後， 會將目前步驟 AWS TOE 標記為 `IgnoredFailure`，並繼續執行下一個步驟。

    AWS TOE 會將父階段的狀態碼和文件設定為 `SuccessWithIgnoredFailure`。
**注意**  
這仍然被視為成功執行，但包含的資訊會讓您知道一或多個步驟失敗並被忽略。
+ *maxAttempts * – 每次重試時，整個步驟和所有反覆運算都會從頭開始執行。
+ *狀態* – 步驟執行的整體狀態。`status` 不代表個別反覆運算的狀態。具有迴圈之步驟的狀態決定如下：
  + 如果單一反覆運算無法執行，步驟的狀態會指向失敗。
  + 如果所有反覆運算都成功，步驟的狀態會指向成功。
+ *startTime * – 步驟執行的整體開始時間。不代表個別反覆運算的開始時間。
+ *endTime * – 步驟執行的整體結束時間。不代表個別反覆運算的結束時間。
+ *failureMessage * – 包含非逾時錯誤時失敗的反覆運算索引。如果發生逾時錯誤，訊息會指出迴圈執行失敗。不會針對每個反覆運算提供個別錯誤訊息，以將失敗訊息的大小降至最低。

## 步驟和反覆運算輸出
<a name="toe-loop-step-output"></a>

每次反覆運算都包含輸出。在迴圈執行結束時， 會 AWS TOE 整合 中所有成功的反覆運算輸出`detailedOutput.json`。合併輸出是屬於動作模組輸出結構描述中定義之對應輸出索引鍵的值定序。下列範例顯示輸出的合併方式：

**適用於反覆運算 1 `ExecuteBash`的 輸出**

```
{
	"stdout":"Hello"
}
```

**適用於反覆運算 2 `ExecuteBash`的 輸出**

```
{
	"stdout":"World"
}
```

**`ExecuteBash`適用於步驟的 輸出**

```
{
	"stdout":"Hello\nWorld"
}
```

例如，`ExecuteBash`、 `ExecutePowerShell`和 `ExecuteBinary`是`STDOUT`作為動作模組輸出傳回的動作模組。`STDOUT`訊息會加入新的行字元，以在 中產生步驟的整體輸出`detailedOutput.json`。

AWS TOE 不會合併失敗反覆運算的輸出。