

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

# 在 中使用條件式建構 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'
```