

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

# CloudFormation 範本 Conditions 語法
<a name="conditions-section-structure"></a>

選用的 `Conditions` 區段包含陳述式來定義在哪些情況下建立或設定實體。例如，您可以建立條件，並將它與資源或輸出建立關聯，使得 CloudFormation 只在條件為 true 時才建立資源或輸出。同樣地，您可以將條件與屬性建立關聯，使得 CloudFormation 只在條件為 true 時才將屬性設為特定的值。如果條件為 false，CloudFormation 會將屬性設為您指定的替代值。

當您想要重複使用範本以在不同的內容 (例如測試環境與生產環境) 中建立資源時，可以使用條件。例如，可以在範本中新增 `EnvironmentType` 輸入參數，此參數接受 `prod` 或 `test` 作為輸入。在 `prod` 環境中，可以包含具有特定功能的 EC2 執行個體；而在 `test` 環境中，就要使用精簡的功能來節省資金。此條件定義可讓您針對每種環境類型來定義要建立哪些資源和其設定方式。

## 語法
<a name="conditions-section-structure-syntax"></a>

`Conditions` 區段由索引鍵名稱 `Conditions` 組成。每個條件宣告都包含邏輯 ID 和一個或多個內建函數。

### 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` 區段中的明確定義。如需這些虛擬參數的詳細資訊，請參閱[使用虛擬參數取得 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)

**注意**  
只有在範本的 `Resources` 區段和 `Outputs` 區段的中繼資料屬性、更新政策屬性和屬性值中，才支援 `Fn::If`。

## 使用 `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 新增為資源的屬性。只有當條件評估為 true 時，CloudFormation 才會建立資源。

#### 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` 內建函數，在資源或輸出中有條件地傳回兩個屬性值的其中之一。此函數會評估條件，如果條件為 true，則傳回一個值，如果條件為 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)主題。