

# CloudFormation テンプレートの Conditions 構文
<a name="conditions-section-structure"></a>

オプションの `Conditions` セクションには、エンティティが作成または設定される状況を定義するステートメントが含まれています。例えば、条件を作成し、それをリソースまたは出力に関連付けることで、条件が true の場合にのみ CloudFormation がリソースまたは出力を作成できるようになります。同様に、条件をプロパティに関連付けて、条件が true の場合にのみ CloudFormation がプロパティを特定の値に設定するようにできます。条件が false の場合、CloudFormation はプロパティをユーザーが指定した代替値に設定します。

テンプレートを再利用して、テスト環境と本番環境などのさまざまなコンテキストでリソースを作成する場合は、条件を使用できます。例えば、テンプレートでは、`prod` または `test` のいずれかを入力として受け取る `EnvironmentType` 入力パラメータを追加できます。`prod` 環境では、特定の機能を備えた EC2 インスタンスを含めることができますが、`test` 環境ではコストを節約するために機能を制限したインスタンスを使用する場合があります。この条件定義により、各環境タイプに応じて作成されるリソースとその構成方法を定義できます。

## 構文
<a name="conditions-section-structure-syntax"></a>

`Conditions` セクションは、キー名 `Conditions` で構成されます。各条件宣言には、論理 ID と 1 つ以上の組み込み関数が含まれます。

### JSON
<a name="conditions-section-structure-syntax.json"></a>

```
"Conditions": {
  "LogicalConditionName1": {
    "Intrinsic function": ...[
  },

  "LogicalConditionName2": {
    "Intrinsic function": ...
  }
}
```

### YAML
<a name="conditions-section-structure-syntax.yaml"></a>

```
Conditions:
  LogicalConditionName1:
    Intrinsic function:
      ...

  LogicalConditionName2:
    Intrinsic function:
      ...
```

## 条件の仕組み
<a name="conditions-section-structure-overview"></a>

条件を使用するには、次の手順に従います。

1. **パラメータ定義の追加** – テンプレートの `Parameters` セクションで条件が評価する入力を定義します。これらの入力パラメータの値に基づいて、条件は true または false と評価されます。擬似パラメータは自動的に利用可能であり、`Parameters` セクションで明示的な定義を必要としないことに注意してください。疑似 Parameters の詳細については、「[擬似パラメータを使用して AWS 値を取得する](pseudo-parameter-reference.md)」を参照してください。

1. **条件定義の追加** – `Fn::If`、`Fn::Equals`、などの組み込み関数を使用して `Conditions` セクションで条件を定義します。これらの条件は、CloudFormation が関連するリソースをいつ作成するかを指定します。条件は以下に基づいて定義できます。
   + 入力または擬似パラメータ値
   + その他の条件
   + 値のマッピング

   ただし、リソースの論理 ID やその属性を条件で参照することはできません。

1. **リソースまたは出力に条件を関連付ける** – `Condition` キーと条件の論理 ID を使用して、リソースまたは出力の条件を参照します。必要に応じて、テンプレートの他の部分 (プロパティ値など) の `Fn::If` を使用して、条件に基づいて値を設定します。詳細については、「[`Condition` キーの使用](#using-conditions-in-templates)」を参照してください。

CloudFormation は、スタックを作成または更新するときに条件を評価します。CloudFormation は、true に関連付けられたエンティティを作成し、false に関連付けられたをエンティティを無視します。また、CloudFormation は、リソースを変更する前に、スタックの更新ごとにこれらの条件を再評価します。true の条件に関連付けられているエンティティは更新され、false の条件に関連付けられているエンティティは削除されます。

**重要**  
スタックの更新時に、条件を単独で更新することはできません。条件を更新できるのは、リソースを追加、変更、または削除する変更を含める場合だけです。

## 条件の組み込み関数
<a name="conditions-section-structure-functions"></a>

次の組み込み関数を使用して条件を定義できます。
+ [https://docs.aws.amazon.com/AWSCloudFormation/latest/TemplateReference/intrinsic-function-reference-conditions.html#intrinsic-function-reference-conditions-and](https://docs.aws.amazon.com/AWSCloudFormation/latest/TemplateReference/intrinsic-function-reference-conditions.html#intrinsic-function-reference-conditions-and)
+ [https://docs.aws.amazon.com/AWSCloudFormation/latest/TemplateReference/intrinsic-function-reference-conditions.html#intrinsic-function-reference-conditions-equals](https://docs.aws.amazon.com/AWSCloudFormation/latest/TemplateReference/intrinsic-function-reference-conditions.html#intrinsic-function-reference-conditions-equals)
+ [https://docs.aws.amazon.com/AWSCloudFormation/latest/TemplateReference/intrinsic-function-reference-foreach.html](https://docs.aws.amazon.com/AWSCloudFormation/latest/TemplateReference/intrinsic-function-reference-foreach.html)
+ [https://docs.aws.amazon.com/AWSCloudFormation/latest/TemplateReference/intrinsic-function-reference-conditions.html#intrinsic-function-reference-conditions-if](https://docs.aws.amazon.com/AWSCloudFormation/latest/TemplateReference/intrinsic-function-reference-conditions.html#intrinsic-function-reference-conditions-if)
+ [https://docs.aws.amazon.com/AWSCloudFormation/latest/TemplateReference/intrinsic-function-reference-conditions.html#intrinsic-function-reference-conditions-not](https://docs.aws.amazon.com/AWSCloudFormation/latest/TemplateReference/intrinsic-function-reference-conditions.html#intrinsic-function-reference-conditions-not)
+ [https://docs.aws.amazon.com/AWSCloudFormation/latest/TemplateReference/intrinsic-function-reference-conditions.html#intrinsic-function-reference-conditions-or](https://docs.aws.amazon.com/AWSCloudFormation/latest/TemplateReference/intrinsic-function-reference-conditions.html#intrinsic-function-reference-conditions-or)

**注記**  
`Fn::If` は、テンプレートの `Resources` セクションと `Outputs` セクションのメタデータ属性、更新ポリシー属性、およびプロパティ値でのみ使用できます。

## `Condition` キーの使用
<a name="using-conditions-in-templates"></a>

条件を定義すると、`Condition` キーを使用して、テンプレート内の `Resources` や `Outputs` などの複数の場所に条件を適用できます。`Condition` キーは条件の論理名を参照し、指定された条件の評価結果を返します。

**Topics**
+ [条件をリソースに関連付ける](#associate-conditions-with-resources)
+ [条件を出力に関連付ける](#associate-conditions-with-outputs)
+ [他の条件での条件の参照](#reference-conditions-in-other-conditions)
+ [`Fn::If` を使用して条件付きでプロパティ値を返す](#conditional-return-property-values-using-fn-if)

### 条件をリソースに関連付ける
<a name="associate-conditions-with-resources"></a>

条件付きでリソースを作成するには、`Condition` キーと条件の論理 ID をリソースの属性として追加します。CloudFormation は、 条件が true に評価される場合にだけ リソースを作成します。

#### JSON
<a name="associate-conditions-with-resources.json"></a>

```
"NewVolume" : {
  "Type" : "AWS::EC2::Volume",
  "Condition" : "IsProduction",
  "Properties" : {
     "Size" : "100",
     "AvailabilityZone" : { "Fn::GetAtt" : [ "EC2Instance", "AvailabilityZone" ]}
  }
}
```

#### YAML
<a name="associate-conditions-with-resources.yaml"></a>

```
NewVolume:
  Type: AWS::EC2::Volume
  Condition: IsProduction
  Properties:
    Size: 100
    AvailabilityZone: !GetAtt EC2Instance.AvailabilityZone
```

### 条件を出力に関連付ける
<a name="associate-conditions-with-outputs"></a>

条件を出力に関連付けることもできます。CloudFormation は、 関連付けられた条件が true に評価された場合にのみ出力を作成します。

#### JSON
<a name="associate-conditions-with-outputs.json"></a>

```
"Outputs" : {
  "VolumeId" : {
    "Condition" : "IsProduction",
    "Value" : { "Ref" : "NewVolume" }
  }
}
```

#### YAML
<a name="associate-conditions-with-outputs.yaml"></a>

```
Outputs:
  VolumeId:
    Condition: IsProduction
    Value: !Ref NewVolume
```

### 他の条件での条件の参照
<a name="reference-conditions-in-other-conditions"></a>

`Conditions` セクションで条件を定義する際、`Condition` キーを使用して他の条件を参照できます。これにより、複数の条件を組み合わせて、より複雑な条件付きロジックを作成できます。

次の例では、`IsProduction` および `IsFeatureEnabled` 条件が true に評価された場合にのみ、`IsProdAndFeatureEnabled` 条件が true に評価されます。

#### JSON
<a name="reference-conditions-in-other-conditions.json"></a>

```
"Conditions": {
  "IsProduction" : {"Fn::Equals" : [{"Ref" : "Environment"}, "prod"]},
  "IsFeatureEnabled" : { "Fn::Equals" : [{"Ref" : "FeatureFlag"}, "enabled"]},
  "IsProdAndFeatureEnabled" : {
    "Fn::And" : [
      {"Condition" : "IsProduction"},
      {"Condition" : "IsFeatureEnabled"}
    ]
  }
}
```

#### YAML
<a name="reference-conditions-in-other-conditions.yaml"></a>

```
Conditions:
  IsProduction:
    !Equals [!Ref Environment, "prod"]
  IsFeatureEnabled:
    !Equals [!Ref FeatureFlag, "enabled"]
  IsProdAndFeatureEnabled: !And
    - !Condition IsProduction
    - !Condition IsFeatureEnabled
```

### `Fn::If` を使用して条件付きでプロパティ値を返す
<a name="conditional-return-property-values-using-fn-if"></a>

より詳細な制御を行う場合には、`Fn::If` 組み込み関数を使用すると、リソースまたは出力内の 2 つのプロパティ値のいずれかを条件付きで返すことができます。この関数は条件を評価し、条件が true の場合は 1 つの値を返し、条件が false の場合は別の値を返します。

#### 条件付きプロパティの値
<a name="using-fn-if-for-conditional-values"></a>

次の例は、環境条件に基づいて EC2 インスタンスタイプを設定する方法を示します。`IsProduction` 条件が true に評価された場合、インスタンスタイプは `c5.xlarge` に設定されます。それ以外の場合、`t3.small` に設定されます。

##### JSON
<a name="using-fn-if-for-conditional-values.json"></a>

```
"Properties" : {
  "InstanceType" : {
    "Fn::If" : [
      "IsProduction",
      "c5.xlarge",
      "t3.small"
    ]
  }
}
```

##### YAML
<a name="using-fn-if-for-conditional-values.yaml"></a>

```
Properties:
  InstanceType: !If
    - IsProduction
    - c5.xlarge
    - t3.small
```

#### 条件付きプロパティの削除
<a name="using-fn-if-with-novalue"></a>

`AWS::NoValue` 擬似パラメータを戻り値として使用し、条件が false の場合に対応するプロパティを削除することもできます。

##### JSON
<a name="using-fn-if-with-novalue.json"></a>

```
"DBSnapshotIdentifier" : {
  "Fn::If" : [
    "UseDBSnapshot",
    {"Ref" : "DBSnapshotName"},
    {"Ref" : "AWS::NoValue"}
  ]
}
```

##### YAML
<a name="using-fn-if-with-novalue.yaml"></a>

```
DBSnapshotIdentifier: !If
  - UseDBSnapshot
  - !Ref DBSnapshotName
  - !Ref "AWS::NoValue"
```

## 例
<a name="conditions-section-structure-examples"></a>

**Topics**
+ [環境ベースのリソースの作成](#environment-based-resource-creation)
+ [複数条件のリソースプロビジョニング](#multi-condition-resource-provisioning)

### 環境ベースのリソースの作成
<a name="environment-based-resource-creation"></a>

次の例では、EC2 インスタンスをプロビジョニングし、環境タイプが `prod` の場合にのみ、条件付きで新しい EBS ボリュームを作成してアタッチします。環境が `test` の場合、追加のボリュームなしで EC2 インスタンスを作成するだけです。

#### JSON
<a name="conditions-section-example-resource-creation.json"></a>

```
{
    "AWSTemplateFormatVersion": "2010-09-09",
    "Parameters": {
        "EnvType": {
            "Description": "Environment type",
            "Default": "test",
            "Type": "String",
            "AllowedValues": [
                "prod",
                "test"
            ],
            "ConstraintDescription": "must specify prod or test"
        }
    },
    "Conditions": {
        "IsProduction": {
            "Fn::Equals": [
                {
                    "Ref": "EnvType"
                },
                "prod"
            ]
        }
    },
    "Resources": {
        "EC2Instance": {
            "Type": "AWS::EC2::Instance",
            "Properties": {
                "ImageId": "ami-1234567890abcdef0",
                "InstanceType": "c5.xlarge"
            }
        },
        "MountPoint": {
            "Type": "AWS::EC2::VolumeAttachment",
            "Condition": "IsProduction",
            "Properties": {
                "InstanceId": {
                    "Ref": "EC2Instance"
                },
                "VolumeId": {
                    "Ref": "NewVolume"
                },
                "Device": "/dev/sdh"
            }
        },
        "NewVolume": {
            "Type": "AWS::EC2::Volume",
            "Condition": "IsProduction",
            "Properties": {
                "Size": 100,
                "AvailabilityZone": {
                    "Fn::GetAtt": [
                        "EC2Instance",
                        "AvailabilityZone"
                    ]
                }
            }
        }
    }
}
```

#### YAML
<a name="conditions-section-example-resource-creation.yaml"></a>

```
AWSTemplateFormatVersion: 2010-09-09
Parameters:
  EnvType:
    Description: Environment type
    Default: test
    Type: String
    AllowedValues:
      - prod
      - test
    ConstraintDescription: must specify prod or test
Conditions:
  IsProduction: !Equals
    - !Ref EnvType
    - prod
Resources:
  EC2Instance:
    Type: AWS::EC2::Instance
    Properties:
      ImageId: ami-1234567890abcdef0
      InstanceType: c5.xlarge
  MountPoint:
    Type: AWS::EC2::VolumeAttachment
    Condition: IsProduction
    Properties:
      InstanceId: !Ref EC2Instance
      VolumeId: !Ref NewVolume
      Device: /dev/sdh
  NewVolume:
    Type: AWS::EC2::Volume
    Condition: IsProduction
    Properties:
      Size: 100
      AvailabilityZone: !GetAtt
        - EC2Instance
        - AvailabilityZone
```

### 複数条件のリソースプロビジョニング
<a name="multi-condition-resource-provisioning"></a>

次の例では、バケット名が指定されている場合、条件付きで S3 バケットを作成し、環境が `prod` に設定されている場合にのみバケットポリシーをアタッチします。バケット名が指定されていない場合、または環境が `test` の場合、リソースは作成されません。

#### JSON
<a name="conditions-section-example-multi-condition.json"></a>

```
{
    "AWSTemplateFormatVersion": "2010-09-09",
    "Parameters": {
        "EnvType": {
            "Type": "String",
            "AllowedValues": [
                "prod",
                "test"
            ]
        },
        "BucketName": {
            "Default": "",
            "Type": "String"
        }
    },
    "Conditions": {
        "IsProduction": {
            "Fn::Equals": [
                {
                    "Ref": "EnvType"
                },
                "prod"
            ]
        },
        "CreateBucket": {
            "Fn::Not": [
                {
                    "Fn::Equals": [
                        {
                            "Ref": "BucketName"
                        },
                        ""
                    ]
                }
            ]
        },
        "CreateBucketPolicy": {
            "Fn::And": [
                {
                    "Condition": "IsProduction"
                },
                {
                    "Condition": "CreateBucket"
                }
            ]
        }
    },
    "Resources": {
        "Bucket": {
            "Type": "AWS::S3::Bucket",
            "Condition": "CreateBucket",
            "Properties": {
                "BucketName": {
                    "Ref": "BucketName"
                }
            }
        },
        "Policy": {
            "Type": "AWS::S3::BucketPolicy",
            "Condition": "CreateBucketPolicy",
            "Properties": {
                "Bucket": {
                    "Ref": "Bucket"
                },
                "PolicyDocument": { ... }
            }
        }
    }
}
```

#### YAML
<a name="conditions-section-example-multi-condition.yaml"></a>

```
AWSTemplateFormatVersion: 2010-09-09
Parameters:
  EnvType:
    Type: String
    AllowedValues:
      - prod
      - test
  BucketName:
    Default: ''
    Type: String
Conditions:
  IsProduction: !Equals
    - !Ref EnvType
    - prod
  CreateBucket: !Not
    - !Equals
      - !Ref BucketName
      - ''
  CreateBucketPolicy: !And
    - !Condition IsProduction
    - !Condition CreateBucket
Resources:
  Bucket:
    Type: AWS::S3::Bucket
    Condition: CreateBucket
    Properties:
      BucketName: !Ref BucketName
  Policy:
    Type: AWS::S3::BucketPolicy
    Condition: CreateBucketPolicy
    Properties:
      Bucket: !Ref Bucket
      PolicyDocument: ...
```

この例では、`CreateBucketPolicy` 条件が、`Condition` キーを使用して他の条件を参照する方法を示しています。ポリシーは、`IsProduction` および `CreateBucket` 条件の両方が true に評価された場合にのみ作成されます。

**注記**  
条件を使用するより複雑な例については、「*CloudFormation テンプレートリファレンスガイド*」の「[Condition 属性](https://docs.aws.amazon.com/AWSCloudFormation/latest/TemplateReference/aws-attribute-condition.html)」トピックを参照してください。