

翻訳は機械翻訳により提供されています。提供された翻訳内容と英語版の間で齟齬、不一致または矛盾がある場合、英語版が優先します。

# で条件付きコンストラクトを使用する AWSTOE
<a name="toe-conditional-constructs"></a>

条件構造は、指定された条件式が `true` と `false` のどちらに評価されるかに基づいて、異なるアクションをコンポーネントドキュメントで実行します。`if` 構造を使用すると、コンポーネントドキュメントの実行フローを制御できます。

## if 構造
<a name="toe-conditional-if"></a>

`if` 構造を使用すると、ステップを実行する必要があるかどうかを評価できます。デフォルトでは、`if` 条件式が `true` に評価されると AWSTOE はステップを実行し、条件が `false` に評価されると AWSTOE はステップをスキップします。ステップがスキップされた場合でも、フェーズとドキュメントが正常に実行されたかどうかを AWSTOE が評価するときは、成功したステップとして扱われます。

**注記**  
`if` ステートメントが評価されるのは 1 回だけです。これは、ステップが再起動をトリガーした場合でも同様です。再起動したステップは、その `if` ステートメントが既に評価されたことを認識し、中断した箇所から続行します。

### 構文
<a name="toe-conditional-if-syntax"></a>

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


| キー名 | 必要 | 説明 | 
| --- | --- | --- | 
| 条件式 | はい |  条件式の最上位には、次のタイプの演算子を 1 つだけ含めることができます。 [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/ja_jp/imagebuilder/latest/userguide/toe-conditional-constructs.html) 式が複数の条件を満たす必要がある場合は、論理演算子を使用して条件を指定します。  | 
| 次に | いいえ |  条件式が `true` に評価された場合に実行するアクションを定義します。  | 
| else | いいえ |  条件式が `false` に評価された場合に実行するアクションを定義します。  | 
| ステップアクション | 条件付き |  `then` または `else` を使用するときは、次のステップアクションのいずれかを指定する必要があります。 [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/ja_jp/imagebuilder/latest/userguide/toe-conditional-constructs.html)  | 

**例 1: パッケージをインストールする**  
 AWSTOE コンポーネントドキュメントの以下のステップ例では、論理演算子を使用してパラメータ値をテストし、パッケージが解凍されている場合は、適切なパッケージマネージャーコマンドを実行してアプリケーションをインストールします。

```
    - 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: ステップをスキップする**  
次の例は、ステップをスキップする 2 つの方法を示しています。1 つは論理演算子を使用し、もう 1 つは比較演算子と `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'
```