

# 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와 하나 이상의 내장 함수가 포함됩니다.

### 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)

**참고**  
템플릿의 `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를 리소스에 속성으로 추가합니다. 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` 키를 사용하여 다른 조건을 참조할 수 있습니다. 이를 통해 여러 조건을 결합하여 더 복잡한 조건부 로직을 생성할 수 있습니다.

다음 예제에서 `IsProdAndFeatureEnabled` 조건은 `IsProduction` 및 `IsFeatureEnabled` 조건이 true로 평가되는 경우에만 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) 주제를 참조하세요.