

# CloudFormation 템플릿 섹션
<a name="template-anatomy"></a>

모든 CloudFormation 템플릿은 하나 이상의 섹션으로 구성되며, 각 섹션에는 특정한 목적이 있습니다.

**Resources** 섹션은 모든 CloudFormation 템플릿에 필요하고 템플릿의 핵심을 구성합니다. 이 섹션은 Amazon EC2 인스턴스 또는 Amazon S3 버킷 같은 스택 리소스 및 해당 속성을 지정합니다. 각 리소스는 고유한 논리적 ID, 유형 및 특정 구성 세부 정보로 정의됩니다.

**Parameters** 섹션은 선택 사항이지만 템플릿을 보다 유연하게 만드는 데 중요한 역할을 합니다. 이를 통해 사용자는 스택을 생성하거나 업데이트할 때 런타임에서 값을 전달할 수 있습니다. `Resources` 및 `Outputs` 섹션에서 이러한 파라미터를 참조할 수 있으므로 템플릿 자체를 변경하지 않고도 사용자 지정할 수 있습니다. 예를 들어, 파라미터를 사용하여 배포마다 달라지는 인스턴스 유형이나 환경 설정을 지정할 수 있습니다.

선택 사항이기도 한 **Outputs** 섹션에서는 스택의 속성을 볼 때 반환되는 값을 정의합니다. Outputs는 리소스 식별자 또는 URL과 같은 유용한 정보를 제공하며, 이러한 정보는 운영 목적이나 다른 스택과의 통합에 활용할 수 있습니다. 이 섹션을 통해 사용자는 템플릿에 의해 생성된 리소스에 대한 중요한 세부 정보를 검색하고 사용할 수 있습니다.

기타 선택 사항인 섹션에는 조건부 값을 관리하는 조회 테이블과 같은 기능을 하는 **Mappings**이 있습니다. 매핑을 사용하면 키-값 페어를 정의하고 `Resources` 및 `Outputs` 섹션의 `Fn::FindInMap` 내장 함수와 함께 이를 사용할 수 있습니다. 이는 AWS 리전 또는 환경 등의 조건에 따라 구성을 조정해야 하는 시나리오에 유용합니다.

**Metadata** 및 **Rules** 섹션은 자주 사용되지 않지만 추가 기능을 제공합니다. `Metadata`는 템플릿에 대한 추가 정보를 포함할 수 있고, `Rules`는 스택 생성 또는 업데이트 중에 파라미터 또는 파라미터 조합의 유효성을 검사하여 특정 기준을 충족하는지 확인합니다. **Conditions** 섹션에서는 환경 유형과 같은 조건에 따라 특정 리소스가 생성되는지 또는 속성에 값이 할당되는지 제어하여 유연성을 더욱 높입니다.

마지막으로 **Transform** 섹션은 템플릿 처리 중 매크로를 적용하는 데 사용됩니다. 서버리스 애플리케이션(Lambda 애플리케이션이라고도 함)의 경우 사용할 [AWS Serverless Application Model(AWS SAM)](https://github.com/awslabs/serverless-application-specification)의 버전을 지정합니다. 변환을 지정할 경우 AWS SAM 구문을 사용하여 템플릿에 리소스를 선언할 수 있습니다. 이 모델은 사용할 수 있는 구문과 처리 방식을 정의합니다. 또한 `AWS::Include` 변환을 사용하여 기본 CloudFormation 템플릿과는 별도로 저장되는 템플릿 스니펫을 포함시킬 수 있습니다.

다음 주제에서는 각 섹션 사용에 대한 자세한 정보와 예제를 제공합니다.

**Topics**
+ [Resources](resources-section-structure.md)
+ [Parameters](parameters-section-structure.md)
+ [Outputs](outputs-section-structure.md)
+ [Mappings](mappings-section-structure.md)
+ [Metadata](metadata-section-structure.md)
+ [Rules](rules-section-structure.md)
+ [Conditions](conditions-section-structure.md)
+ [Transform](transform-section-structure.md)
+ [포맷 버전](format-version-structure.md)
+ [Description](template-description-structure.md)

# CloudFormation 템플릿 Resources 구문
<a name="resources-section-structure"></a>

`Resources` 섹션은 CloudFormation 템플릿의 필수 최상위 섹션입니다. CloudFormation에서 스택의 일부로 프로비저닝 및 구성하려는 AWS 리소스를 선언합니다.

## 구문
<a name="resources-section-structure-syntax"></a>

`Resources` 섹션에서는 다음 구문을 사용합니다.

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

```
"Resources" : {
    "LogicalResourceName1" : {
        "Type" : "AWS::ServiceName::ResourceType",
        "Properties" : {
            "PropertyName1" : "PropertyValue1",
            ...
        }
    },

    "LogicalResourceName2" : {
        "Type" : "AWS::ServiceName::ResourceType",
        "Properties" : {
            "PropertyName1" : "PropertyValue1",
            ...
        }
    }
}
```

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

```
Resources:
  LogicalResourceName1:
    Type: AWS::ServiceName::ResourceType
    Properties:
      PropertyName1: PropertyValue1
      ...

  LogicalResourceName2:
    Type: AWS::ServiceName::ResourceType
    Properties:
      PropertyName1: PropertyValue1
      ...
```

## 논리적 ID(**논리명이라고도 함)
<a name="resources-section-logical-id"></a>

CloudFormation 템플릿 내에서 리소스는 논리적 이름으로 식별됩니다. 이 이름은 영숫자(A-Z, a-z, 0-9)여야 하며 템플릿 내에서 고유해야 합니다. 논리명은 템플릿의 다른 섹션에 있는 리소스를 참조하는 데 사용됩니다.

## 리소스 유형
<a name="resources-section-resource-type"></a>

각 리소스에는 `Type` 속성이 있어야 하며, 이 속성은 AWS 리소스의 종류를 정의합니다. `Type` 속성은 `AWS::ServiceName::ResourceType` 형식을 갖습니다. 예를 들어, Amazon S3 버킷의 `Type` 속성은 `AWS::S3::Bucket`입니다.

지원되는 리소스 유형의 전체 목록은 [AWS 리소스 및 속성 유형 참조](https://docs.aws.amazon.com/AWSCloudFormation/latest/TemplateReference/aws-template-resource-type-ref.html)를 참조하세요.

## 리소스 속성
<a name="resources-section-resource-properties"></a>

리소스 속성은 특정 리소스 유형에 대한 구성 세부 정보를 정의하기 위해 지정할 수 있는 추가 옵션입니다. 일부 속성은 필수이고, 선택 사항인 속성도 있습니다. 일부 속성에는 기본값이 있으므로 해당 속성을 지정하는 것은 선택 사항입니다.

각 리소스 유형에 지원되는 속성에 대한 자세한 내용은 [AWS 리소스 및 속성 유형 참조](https://docs.aws.amazon.com/AWSCloudFormation/latest/TemplateReference/aws-template-resource-type-ref.html)의 주제를 참조하세요.

속성값은 리터럴 문자열, 문자열 목록, 부울, 동적 참조, 파라미터 참조, 가상 참조 또는 함수가 반환하는 값 중 하나일 수 있습니다. 다음 예제에서는 다양한 속성 값 유형을 선언하는 방법을 보여줍니다.

### JSON
<a name="resource-properties-example.json"></a>

```
"Properties" : {
    "String" : "A string value",
    "Number" : 123,
    "LiteralList" : [ "first-value", "second-value" ],
    "Boolean" : true
}
```

### YAML
<a name="resource-properties-example.yaml"></a>

```
Properties:
  String: A string value 
  Number: 123
  LiteralList:
    - first-value
    - second-value
  Boolean: true
```

## 물리적 ID
<a name="resources-section-physical-id"></a>

논리적 ID 외에도, 특정 리소스에는 EC2 인스턴스 ID 또는 S3 버킷 이름 같은 해당 리소스에 대해 실제 할당된 이름인 물리적 ID도 지정됩니다. 물리적 ID를 사용하여 CloudFormation 템플릿 외부에 있는 리소스를 식별할 수 있지만 이는 리소스가 생성된 후에만 가능합니다. 예를 들어 EC2 인스턴스에 논리적 ID `MyEC2Instance`의 리소스를 제공한다고 가정하겠습니다. CloudFormation에서 인스턴스를 생성할 때 CloudFormation은 자동적으로 물리적 ID(예: `i-1234567890abcdef0`)를 생성하여 인스턴스에 할당합니다. 이 물리적 ID를 사용하면 Amazon EC2 콘솔에서 인스턴스를 식별하고 인스턴스의 속성(예: DNS 이름)을 볼 수 있습니다.

Amazon S3 버킷과 기타 여러 리소스의 경우 사용자가 명시적으로 지정하지 않으면 CloudFormation이 리소스에 대한 고유한 물리명을 자동으로 생성합니다. 이 물리명은 CloudFormation 스택의 이름, CloudFormation 템플릿에 지정된 리소스의 논리명, 고유 ID의 조합을 기반으로 합니다. 예를 들어, `MyStack`이라는 스택에 논리명이 `MyBucket`인 Amazon S3 버킷이 있는 경우 CloudFormation은 `MyStack-MyBucket-abcdefghijk1`이라는 물리적 이름으로 버킷의 이름을 지정할 수 있습니다.

사용자 지정 이름을 지원하는 리소스의 경우, 물리적 이름을 할당하면 리소스를 보다 신속하게 식별할 수 있습니다. 예를 들면 로그를 저장하는 S3 버킷에 `MyPerformanceLogs` 이름을 지정할 수 있습니다. 자세한 내용은 [이름 유형](https://docs.aws.amazon.com/AWSCloudFormation/latest/TemplateReference/aws-properties-name.html)을 참조하세요.

## 참조 리소스
<a name="using-cross-resource-references"></a>

다른 리소스의 이름이나 속성을 기반으로 한 리소스의 속성을 설정해야 하는 경우가 있습니다. 예를 들어, S3 버킷이 지원하는 CloudFront 배포 또는 EC2 보안 그룹을 사용하는 EC2 인스턴스를 생성할 수 있습니다. 이러한 모든 리소스는 동일한 CloudFormation 템플릿에서 생성할 수 있습니다.

CloudFormation은 다른 리소스 및 해당 속성을 참조하는 데 사용할 수 있는 내장 함수를 제공합니다. 이러한 함수를 사용하면 리소스 간에 종속성을 생성하고 한 리소스에서 다른 리소스로 값을 전달할 수 있습니다.

### `Ref` 함수
<a name="resource-properties-ref"></a>

`Ref` 함수는 대체로 동일한 CloudFormation 템플릿 내에 정의된 리소스의 식별 속성을 검색하는 데 사용됩니다. 반환되는 내용은 리소스 유형에 따라 달라집니다. 대부분의 리소스는 리소스의 물리명을 반환합니다. 하지만 일부 리소스 유형의 경우 `AWS::EC2::EIP` 리소스의 IP 주소나 Amazon SNS 주제의 Amazon 리소스 이름(ARN) 등의 다른 값을 반환할 수 있습니다.

다음 예제는 속성에서 `Ref` 함수의 사용 방법을 설명합니다. 각 예제에서 `Ref` 함수는 템플릿의 다른 곳에서 선언된 `LogicalResourceName` 리소스의 실제 이름을 반환합니다. YAML 예제의 `!Ref` 구문 예제는 `Ref` 함수를 보다 간단하게 작성하는 방법입니다.

#### JSON
<a name="resource-properties-ref-example.json"></a>

```
"Properties" : {
    "PropertyName" : { "Ref" : "LogicalResourceName" }
}
```

#### YAML
<a name="resource-properties-ref-example.yaml"></a>

```
Properties:
  PropertyName1:
    Ref: LogicalResourceName
  PropertyName2: !Ref LogicalResourceName
```

`Ref` 함수에 대한 더 자세한 내용은 [https://docs.aws.amazon.com/AWSCloudFormation/latest/TemplateReference/intrinsic-function-reference-ref.html](https://docs.aws.amazon.com/AWSCloudFormation/latest/TemplateReference/intrinsic-function-reference-ref.html)를 참조하세요.

### `Fn::GetAtt` 함수
<a name="resource-properties-getatt"></a>

`Ref` 함수는 리소스에 대해 반환되는 파라미터나 값이 정확히 원하는 값인 경우에 유용합니다. 그러나 리소스의 다른 속성이 필요할 수 있습니다. 예를 들어 S3 오리진을 사용하여 CloudFront 배포를 생성하려는 경우 DNS 스타일 주소를 사용하여 버킷 위치를 지정해야 합니다. 일부 리소스에는 템플릿에서 사용할 수 있는 값이 지정되는 추가 속성이 있습니다. 이러한 속성을 가져오려면 `Fn::GetAtt` 함수를 사용합니다.

다음 예제는 속성에서 `GetAtt` 함수의 사용 방법을 설명합니다. `Fn::GetAtt` 함수는 두 개 파라미터, 리소스의 논리적 이름, 그리고 검색할 속성의 이름을 사용합니다. YAML 예제의 `!GetAtt` 구문 예제는 `GetAtt` 함수를 보다 간단하게 작성하는 방법입니다.

#### JSON
<a name="resource-properties-getatt-example.json"></a>

```
"Properties" : {
    "PropertyName" : {
        "Fn::GetAtt" : [ "LogicalResourceName", "AttributeName" ]
    }
}
```

#### YAML
<a name="resource-properties-getatt-example.yaml"></a>

```
Properties:
  PropertyName1:
    Fn::GetAtt:
      - LogicalResourceName
      - AttributeName
  PropertyName2: !GetAtt LogicalResourceName.AttributeName
```

`GetAtt` 함수에 대한 더 자세한 내용은 [https://docs.aws.amazon.com/AWSCloudFormation/latest/TemplateReference/intrinsic-function-reference-getatt.html](https://docs.aws.amazon.com/AWSCloudFormation/latest/TemplateReference/intrinsic-function-reference-getatt.html)를 참조하세요.

## 예제
<a name="resources-section-structure-examples"></a>

다음 예제는 리소스를 선언하는 방법과 CloudFormation 템플릿이 동일한 템플릿 내에 정의된 다른 리소스와 기존 AWS 리소스를 참조하는 방법을 보여줍니다.

**Topics**
+ [

### 사용자 지정 이름을 사용하여 단일 리소스 선언
](#resources-section-structure-examples-single-resource)
+ [

### `Ref` 함수로 다른 리소스 참조
](#resources-section-structure-examples-ref)
+ [

### `Fn::GetAtt` 함수를 사용하여 리소스 속성 참조
](#resources-section-structure-examples-getatt)

### 사용자 지정 이름을 사용하여 단일 리소스 선언
<a name="resources-section-structure-examples-single-resource"></a>

다음 예제에서는 논리명이 `MyBucket`인 `AWS::S3::Bucket` 유형의 단일 리소스를 선언합니다. `BucketName` 속성이 *amzn-s3-demo-bucket*으로 설정되는데, 이를 원하는 S3 버킷 이름으로 바꿔야 합니다.

이 리소스 선언을 사용하여 스택을 생성할 경우 CloudFormation에서는 기본 설정으로 Amazon S3 버킷을 생성합니다. Amazon EC2 인스턴스나 Auto Scaling 그룹 같은 기타 리소스의 경우 CloudFormation은 추가 정보를 요구합니다.

#### JSON
<a name="resources-section-structure-examples-single-resource.json"></a>

```
{
    "Resources": {
        "MyBucket": {
            "Type": "AWS::S3::Bucket",
            "Properties": {
                "BucketName": "amzn-s3-demo-bucket"
            }
        }
    }
}
```

#### YAML
<a name="resources-section-structure-examples-single-resource.yaml"></a>

```
Resources:
  MyBucket:
    Type: AWS::S3::Bucket
    Properties:
      BucketName: amzn-s3-demo-bucket
```

### `Ref` 함수로 다른 리소스 참조
<a name="resources-section-structure-examples-ref"></a>

다음 예제는 EC2 인스턴스와 보안 그룹을 정의하는 리소스 선언을 보여줍니다. `Ec2Instance` 리소스는 `Ref` 함수를 사용하여 해당 `SecurityGroupIds` 속성의 일부로 `InstanceSecurityGroup` 리소스를 참조합니다. 템플릿에 선언되지 않은 기존 보안 그룹(`sg-12a4c434`)도 포함됩니다. 리터럴 문자열을 사용하여 기존 AWS 리소스를 참조합니다.

#### JSON
<a name="resources-section-structure-examples-ref.json"></a>

```
{
    "Resources": {
        "Ec2Instance": {
            "Type": "AWS::EC2::Instance",
            "Properties": {
                "SecurityGroupIds": [
                    {
                        "Ref": "InstanceSecurityGroup"
                    },
                    "sg-12a4c434"
                ],
                "KeyName": "MyKey",
                "ImageId": "ami-1234567890abcdef0"
            }
        },
        "InstanceSecurityGroup": {
            "Type": "AWS::EC2::SecurityGroup",
            "Properties": {
                "GroupDescription": "Enable SSH access via port 22",
                "SecurityGroupIngress": [
                    {
                        "IpProtocol": "tcp",
                        "FromPort": 22,
                        "ToPort": 22,
                        "CidrIp": "0.0.0.0/0"
                    }
                ]
            }
        }
    }
}
```

#### YAML
<a name="resources-section-structure-examples-ref.yaml"></a>

```
Resources:
  Ec2Instance:
    Type: AWS::EC2::Instance
    Properties:
      SecurityGroupIds:
        - !Ref InstanceSecurityGroup
        - sg-12a4c434
      KeyName: MyKey
      ImageId: ami-1234567890abcdef0
  InstanceSecurityGroup:
    Type: AWS::EC2::SecurityGroup
    Properties:
      GroupDescription: Enable SSH access via port 22
      SecurityGroupIngress:
        - IpProtocol: tcp
          FromPort: 22
          ToPort: 22
          CidrIp: 0.0.0.0/0
```

### `Fn::GetAtt` 함수를 사용하여 리소스 속성 참조
<a name="resources-section-structure-examples-getatt"></a>

다음 예제에서는 CloudFront 배포 리소스와 S3 버킷을 정의하는 리소스 선언을 보여줍니다. `MyDistribution` 리소스는 버킷의 `DomainName` 속성을 가져오는 `Fn::GetAtt` 함수를 사용하여 `MyBucket` 리소스의 DNS 이름을 지정합니다. `Fn::GetAtt` 함수는 두 파라미터를 어레이 형태로 나열합니다. 여러 파라미터를 사용하는 함수의 경우 어레이를 사용하여 파라미터를 지정합니다.

#### JSON
<a name="resources-section-structure-examples-getatt.json"></a>

```
{
  "Resources": {
    "MyBucket": {
      "Type": "AWS::S3::Bucket"
    },
    "MyDistribution": {
      "Type": "AWS::CloudFront::Distribution",
      "Properties": {
        "DistributionConfig": {
          "Origins": [
            {
              "DomainName": {
                "Fn::GetAtt": [
                  "MyBucket",
                  "DomainName"
                ]
              },
              "Id": "MyS3Origin",
              "S3OriginConfig": {}
            }
          ],
          "Enabled": "true",
          "DefaultCacheBehavior": {
            "TargetOriginId": "MyS3Origin",
            "ForwardedValues": {
              "QueryString": "false"
            },
            "ViewerProtocolPolicy": "allow-all"
          }
        }
      }
    }
  }
}
```

#### YAML
<a name="resources-section-structure-examples-getatt.yaml"></a>

```
Resources:
  MyBucket:
    Type: AWS::S3::Bucket
  MyDistribution:
    Type: AWS::CloudFront::Distribution
    Properties:
      DistributionConfig:
        Origins:
          - DomainName: !GetAtt 
              - MyBucket
              - DomainName
            Id: MyS3Origin
            S3OriginConfig: {}
        Enabled: 'true'
        DefaultCacheBehavior:
          TargetOriginId: MyS3Origin
          ForwardedValues:
            QueryString: 'false'
          ViewerProtocolPolicy: allow-all
```

# CloudFormation 템플릿 Parameters 구문
<a name="parameters-section-structure"></a>

선택 사항인 `Parameters` 단원을 사용하여 템플릿을 사용자 지정합니다. 파라미터를 통해 스택을 생성하거나 업데이트 할 때마다 템플릿에 사용자 지정 값을 입력할 수 있습니다. 템플릿에 파라미터를 사용하여 특정 시나리오에 맞게 조정할 수 있는 재사용 가능하고 유연한 템플릿을 만들 수 있습니다.

적절한 유형의 파라미터를 정의하여 콘솔로 스택을 생성할 때 기존 리소스의 식별자 목록에서 선택할 수 있습니다. 자세한 내용은 [CloudFormation에서 제공하는 파라미터 유형을 사용하여 런타임 시 기존 리소스 지정](cloudformation-supplied-parameter-types.md) 섹션을 참조하세요.

파라미터는 스택 리소스의 속성 값을 지정하는 데 주로 사용되는 방법입니다. 그러나 리전에 따라 달라지는 설정이 있거나 다른 조건이나 종속성으로 인해 사용자가 파악하기 어려운 설정이 있을 수 있습니다. 이러한 경우 원하는 결과를 얻기 위해 보다 간단한 값을 지정할 수 있도록(또는 전혀 지정할 필요가 없도록) 템플릿에 몇 가지 논리를 추가하는 것이 좋습니다(예: 매핑 사용). 자세한 내용은 [CloudFormation 템플릿 Mappings 구문](mappings-section-structure.md) 섹션을 참조하세요.

## 구문
<a name="parameters-section-structure-syntax"></a>

다음 일반 구문을 사용하는 템플릿의 `Parameters` 섹션에서 파라미터를 선언합니다.

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

```
"Parameters" : {
  "ParameterLogicalID" : {
    "Description": "Information about the parameter",
    "Type" : "DataType",
    "Default" : "value",
    "AllowedValues" : ["value1", "value2"]
  }
}
```

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

```
Parameters:
  ParameterLogicalID:
    Description: Information about the parameter
    Type: DataType
    Default: value
    AllowedValues:
      - value1
      - value2
```

파라미터에는 해당 값과 값에 대한 구속 조건을 정의하는 속성 목록이 포함됩니다. 유일한 필수 속성은 `Type`(`String`, `Number` 또는 CloudFormation에서 제공하는 파라미터 유형일 수 있음)입니다. 사용자가 지정해야 하는 값의 종류에 대해 설명하는 `Description` 속성을 추가할 수도 있습니다. 파라미터의 이름과 설명은 **스택 생성** 마법사에서 템플릿을 사용할 때 **파라미터 지정** 페이지에 나타납니다.

**참고**  
기본적으로 CloudFormation 콘솔에는 입력 파라미터가 논리적 ID에 따라 영문자순으로 나열됩니다. 이 기본 순서를 재정의하고 관련 파라미터를 함께 그룹화하려면 템플릿의 `AWS::CloudFormation::Interface` 메타데이터 키를 사용할 수 있습니다. 자세한 내용은 [`AWS::CloudFormation::Interface` 메타데이터를 사용하여 CloudFormation 파라미터 구성](aws-cloudformation-interface.md) 섹션을 참조하세요.

기본값이 있는 파라미터의 경우 CloudFormation에서는 사용자가 다른 값을 지정하지 않을 경우 기본값이 사용됩니다. 기본 속성을 생략하는 경우 사용자가 해당 파라미터에 대한 값을 지정해야 합니다. 그러나 사용자에게 값을 입력하도록 요구한다고 해서 해당 값의 유효성이 보장되는 것은 아닙니다. 파라미터 값을 검증하려는 경우 제약을 선언하거나 AWS 특정 유형을 지정할 수 있습니다.

기본값이 없는 파라미터의 경우 사용자는 스택 생성 시 키 이름 값을 지정해야 합니다. 지정하지 않을 경우 CloudFormation에서 스택을 생성할 수 없으며 다음 예외가 발생합니다.

```
Parameters: [KeyName] must have values
```

## 속성
<a name="parameters-section-structure-properties"></a>

`AllowedPattern`  
`String` 또는 `CommaDelimitedList` 유형에 허용할 패턴을 나타내는 정규식입니다. `String` 파라미터 유형에 적용할 경우 패턴이 제공된 전체 파라미터값과 일치해야 합니다. `CommaDelimitedList` 파라미터 유형에 적용할 경우 패턴이 목록의 각 값과 일치해야 합니다.  
*필수 항목 여부*: 아니요

`AllowedValues`  
파라미터에 허용되는 값 목록을 포함하는 어레이입니다. `String` 파라미터 유형에 적용할 경우 파라미터값은 허용된 값 중 하나여야 합니다. `CommaDelimitedList` 파라미터 유형에 적용할 경우 목록의 각 값은 지정된 허용된 값 중 하나여야 합니다.  
*필수 항목 여부*: 아니요  
YAML을 사용하면서 `AllowedValues`에 `Yes` 및 `No` 문자열을 사용하려는 경우 작은따옴표를 사용하여 YAML 구문 분석기가 이러한 부울 값을 고려하지 않도록 합니다.

`ConstraintDescription`  
제약 위반 시 해당 제약을 설명하는 문자열입니다. 예를 들어 제약 설명이 없으면 `[A-Za-z0-9]+` 패턴이 허용된 파라미터에 사용자가 유효하지 않은 값을 지정할 때 다음과 같은 오류 메시지가 표시됩니다.  
`Malformed input-Parameter MyParameter must match pattern [A-Za-z0-9]+`  
*'문자(대문자 및 소문자)와 숫자만 포함시킬 수 있음'* 같은 제약을 추가, 다음과 같은 사용자 지정 오류 메시지를 표시할 수 있습니다.  
`Malformed input-Parameter MyParameter must only contain uppercase and lowercase letters and numbers`  
*필수 항목 여부*: 아니요

`Default`  
스택 생성 시 지정된 값이 없는 경우에 사용할 템플릿에 적합한 유형의 값입니다. 파라미터에 대한 제약을 정의하는 경우 이러한 제약을 준수하는 값을 지정해야 합니다.  
*필수 항목 여부*: 아니요

`Description`  
파라미터를 설명하는 최대 4000자 문자열입니다.  
*필수 항목 여부*: 아니요

`MaxLength`  
`String` 유형에 허용할 최대 문자 수를 결정하는 정수 값입니다.  
*필수 항목 여부*: 아니요

`MaxValue`  
`Number` 유형에 허용할 최대 숫자 값을 결정하는 숫자 값입니다.  
*필수 항목 여부*: 아니요

`MinLength`  
`String` 유형에 허용할 최소 문자 수를 결정하는 정수 값입니다.  
*필수 항목 여부*: 아니요

`MinValue`  
`Number` 유형에 허용할 최소 숫자 값을 결정하는 숫자 값입니다.  
*필수 항목 여부*: 아니요

`NoEcho`  
콘솔, 명령줄 도구 또는 API에 표시되지 않도록 파라미터값을 마스킹 처리할지 여부입니다. `NoEcho` 속성을 `true`로 설정한 경우, 아래 지정된 위치에 저장된 정보를 제외하고 CloudFormation은 스택 또는 스택 이벤트를 설명하는 모든 호출에 대해 별표(\$1\$1\$1\$1\$1)로 마스킹 처리된 파라미터값을 반환합니다.  
*필수 항목 여부*: 아니요  
`NoEcho` 속성을 사용해도 다음에 저장된 정보는 마스킹되지 않습니다.  
+ `Metadata` 템플릿 섹션. CloudFormation은 `Metadata` 섹션에 포함된 정보를 변환, 수정 또는 삭제하지 않습니다. 자세한 내용은 [메타데이터](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/metadata-section-structure.html)를 참조하십시오.
+ `Outputs` 템플릿 섹션. 자세한 내용은 [출력](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/outputs-section-structure.html)을 참조하십시오.
+ 리소스 정의의 `Metadata` 속성입니다. 자세한 내용은 [`Metadata` 속성](https://docs.aws.amazon.com/AWSCloudFormation/latest/TemplateReference/aws-attribute-metadata.html)을 참조하세요.
이러한 메커니즘을 사용하여 암호나 보안 정보와 같은 중요한 정보를 포함하지 않는 것이 좋습니다.
AWS Systems Manager Parameter Store 또는 AWS Secrets Manager와 같이 CloudFormation 외부에서 저장 및 관리되는 중요한 정보를 참조하려면 CloudFormation 템플릿에 직접 중요한 정보를 포함하는 대신 스택 템플릿에 있는 동적 파라미터를 사용하는 것이 좋습니다.  
자세한 내용은 [템플릿에 자격 증명을 포함하지 않음](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/security-best-practices.html#creds)을 참조하십시오.
리소스의 기본 식별자의 일부인 리소스 속성에 `NoEcho` 파라미터 또는 민감한 데이터를 포함하지 않는 것이 좋습니다.  
기본 리소스 식별자를 구성하는 속성에 `NoEcho` 파라미터가 포함된 경우 CloudFormation은 기본 리소스 식별자에서 **실제 일반 텍스트값을 사용할 수 있습니다. 이 리소스 ID는 파생된 출력 또는 대상에 나타날 수 있습니다.  
리소스 유형의 기본 식별자를 구성하는 리소스 속성을 확인하려면 [AWS 리소스 및 속성 유형 참조](https://docs.aws.amazon.com/AWSCloudFormation/latest/TemplateReference/aws-template-resource-type-ref.html)에서 해당 리소스에 대한 리소스 참조 설명서를 참조하세요. **Return values**(반환 값) 섹션에서 `Ref` 함수 반환 값은 리소스 유형의 기본 식별자를 구성하는 리소스 속성을 나타냅니다.

`Type`  <a name="parameters-section-structure-properties-type"></a>
파라미터(`DataType`)의 데이터 유형입니다.  
*필수 항목 여부:* 예  
CloudFormation은 다음과 같은 파라미터 유형을 지원합니다.    
`String`  
리터럴 문자열입니다. `MinLength`, `MaxLength`, `Default`, `AllowedValues` 및 `AllowedPattern` 속성을 사용하여 제약 조건을 선언할 수 있습니다.  
예를 들면 사용자는 `"MyUserName"`을 지정할 수 있습니다.  
`Number`  
정수 또는 부동 소수점. CloudFormation에서 파라미터값이 숫자로 확인되지만, 템플릿 내 다른 곳에서 이 파라미터를 사용하는 경우(예를 들어, `Ref` 내장 함수를 사용하여) 파라미터값이 문자열이 됩니다.  
`MinValue`, `MaxValue`, `Default` 및 `AllowedValues` 속성을 사용하여 제약 조건을 선언할 수 있습니다.  
예를 들면 사용자는 `"8888"`을 지정할 수 있습니다.  
`List<Number>`  
쉼표로 구분된 정수 또는 부동 소수점의 배열. CloudFormation에서 파라미터값이 숫자로 확인되지만, 템플릿 내 다른 곳에서 이 파라미터를 사용하는 경우(예를 들어, `Ref` 내장 함수를 사용하여) 파라미터값이 문자열 목록이 됩니다.  
예를 들어 사용자가 `"80,20"`을 지정하면 `Ref`는 `["80","20"]`이 됩니다.  
`CommaDelimitedList`  
쉼표로 구분된 리터럴 문자열 어레이입니다. 총 문자열 수는 총 쉼표 수보다 하나 더 많아야 합니다. 또한 각 멤버 문자열에는 공백이 삽입됩니다.  
예를 들어 사용자가 `"test,dev,prod"`을 지정하면 `Ref`는 `["test","dev","prod"]`이 됩니다.  
AWS 특정 파라미터 유형  
Amazon EC2 키 페어 이름 및 VPC ID와 같은 AWS 값입니다. 자세한 내용은 [런타임 시 기존 리소스 지정](cloudformation-supplied-parameter-types.md) 섹션을 참조하세요.  
Systems Manager 파라미터 유형  
시스템 관리자 Parameter Store의 기존 파라미터에 해당되는 파라미터. Systems Manager 파라미터 키를 Systems Manager 파라미터 유형 값으로 지정합니다. 그러면 CloudFormation이 Parameter Store에서 스택에 사용할 최신 값을 검색합니다. 자세한 내용은 [런타임 시 기존 리소스 지정](cloudformation-supplied-parameter-types.md) 섹션을 참조하세요.

## 파라미터의 일반 요구 사항
<a name="parameters-section-structure-requirements"></a>

파라미터를 사용할 때는 다음 요구 사항이 적용됩니다.
+ CloudFormation 템플릿에는 최대 200개의 파라미터를 지정할 수 있습니다.
+ 파라미터마다 논리명(논리적 ID)을 지정해야 합니다. 이 이름은 템플릿 내 모든 논리명 간에 고유해야 하며 영숫자로 지정해야 합니다.
+ 파라미터마다 CloudFormation에서 지원하는 파라미터 유형을 할당해야 합니다. 자세한 내용은 [유형](#parameters-section-structure-properties-type)을 참조하십시오.
+ 파라미터마다 런타임에 값을 할당해야 CloudFormation이 스택을 성공적으로 프로비저닝할 수 있습니다. 다른 값이 제공되는 경우를 제외하고, CloudFormation에 대한 기본값을 선택적으로 지정할 수 있습니다.
+ 파라미터는 동일한 템플릿에서 선언하고 참조해야 합니다. 템플릿의 `Resources` 및 `Outputs`의 파라미터를 참조할 수 있습니다.

## 예제
<a name="parameters-section-examples"></a>

**Topics**
+ [

### 단순 문자열 파라미터
](#parameters-section-structure-example-1)
+ [

### 암호 파라미터
](#parameters-section-structure-example-2)
+ [

### 파라미터 참조
](#parameters-section-structure-example-3)
+ [

### 쉼표로 구분된 목록 파라미터
](#parameters-section-structure-example-4)
+ [

### 쉼표로 구분된 목록 파라미터에서 값 반환
](#parameters-section-structure-example-5)

### 단순 문자열 파라미터
<a name="parameters-section-structure-example-1"></a>

다음 예제는 `String` 유형의 `InstanceTypeParameter`라는 파라미터를 선언합니다. 스택의 Amazon EC2 인스턴스 유형을 지정할 수 있는 파라미터입니다. 스택 생성 또는 업데이트 중 값이 제공되지 않으면 CloudFormation은 기본값인 `t2.micro`를 사용합니다.

#### JSON
<a name="parameters-section-structure-example-1.json"></a>

```
"Parameters" : {
  "InstanceTypeParameter" : {
    "Description" : "Enter t2.micro, m1.small, or m1.large. Default is t2.micro.",
    "Type" : "String",
    "Default" : "t2.micro",
    "AllowedValues" : ["t2.micro", "m1.small", "m1.large"]
  }
}
```

#### YAML
<a name="parameters-section-structure-example-1.yaml"></a>

```
Parameters:
  InstanceTypeParameter:
    Description: Enter t2.micro, m1.small, or m1.large. Default is t2.micro.
    Type: String
    Default: t2.micro
    AllowedValues:
      - t2.micro
      - m1.small
      - m1.large
```

### 암호 파라미터
<a name="parameters-section-structure-example-2"></a>

다음 예제는 기본값 없이 `String` 유형의 `DBPwd`라는 파라미터를 선언합니다. `NoEcho` 속성을 `true`로 설정하면 파라미터값이 스택 설명에 표시되지 않습니다. 지정할 수 있는 최소 길이는 `1`이고, 지정할 수 있는 최대 길이는 `41`입니다. 이 패턴에는 영문자 소문자/대문자와 숫자가 허용됩니다. 이 예제에서는 `AllowedPattern` 속성에 정규식을 사용하는 방법도 보여줍니다.

#### JSON
<a name="parameters-section-structure-example-2.json"></a>

```
"Parameters" : {
  "DBPwd" : {
    "NoEcho" : "true",
    "Description" : "The database admin account password",
    "Type" : "String",
    "MinLength" : "1",
    "MaxLength" : "41",
    "AllowedPattern" : "^[a-zA-Z0-9]*$"
  }
}
```

#### YAML
<a name="parameters-section-structure-example-2.yaml"></a>

```
Parameters: 
  DBPwd: 
    NoEcho: true
    Description: The database admin account password
    Type: String
    MinLength: 1
    MaxLength: 41
    AllowedPattern: ^[a-zA-Z0-9]*$
```

### 파라미터 참조
<a name="parameters-section-structure-example-3"></a>

`Ref` 내장 함수를 사용하여 파라미터를 참조할 수 있고, CloudFormation은 스택 프로비저닝에 이 파라미터값을 사용합니다. 동일한 템플릿의 `Resources` 및 `Outputs`의 파라미터를 참조할 수 있습니다.

다음은 EC2 인스턴스의 `InstanceType` 속성이 `InstanceTypeParameter` 파라미터값을 참조하는 예제입니다.

#### JSON
<a name="parameters-section-structure-example-3.json"></a>

```
"Ec2Instance" : {
  "Type" : "AWS::EC2::Instance",
  "Properties" : {
    "InstanceType" : { "Ref" : "InstanceTypeParameter" },
    "ImageId" : "ami-0ff8a91507f77f867"
  }
}
```

#### YAML
<a name="parameters-section-structure-example-3.yaml"></a>

```
Ec2Instance:
  Type: AWS::EC2::Instance
  Properties:
    InstanceType:
      Ref: InstanceTypeParameter
    ImageId: ami-0ff8a91507f77f867
```

### 쉼표로 구분된 목록 파라미터
<a name="parameters-section-structure-example-4"></a>

`CommaDelimitedList` 파라미터 유형은 단일 속성에 여러 값을 제공해야 할 때 유용할 수 있습니다. 다음 예제는 쉼표로 구분된 3개의 CIDR 블록을 기본값으로 사용하여 `DbSubnetIpBlocks`라는 파라미터를 선언합니다.

#### JSON
<a name="parameters-section-structure-example-4.json"></a>

```
"Parameters" : {
  "DbSubnetIpBlocks": {
    "Description": "Comma-delimited list of three CIDR blocks",
    "Type": "CommaDelimitedList",
    "Default": "10.0.48.0/24, 10.0.112.0/24, 10.0.176.0/24"
  }
}
```

#### YAML
<a name="parameters-section-structure-example-4.yaml"></a>

```
Parameters: 
  DbSubnetIpBlocks: 
    Description: "Comma-delimited list of three CIDR blocks"
    Type: CommaDelimitedList
    Default: "10.0.48.0/24, 10.0.112.0/24, 10.0.176.0/24"
```

### 쉼표로 구분된 목록 파라미터에서 값 반환
<a name="parameters-section-structure-example-5"></a>

파라미터의 쉼표로 구분된 목록에서 특정 값을 참조하려면 템플릿의 `Resources` 섹션에서 `Fn::Select` 내장 함수를 사용합니다. 다음 예제와 같이 원하는 객체의 인덱스 값과 객체 목록을 전달합니다.

#### JSON
<a name="parameters-section-structure-example-5.json"></a>

```
{
    "Parameters": {
        "VPC": {
            "Type": "String",
            "Default": "vpc-123456"
        },
        "VpcAzs": {
            "Type": "CommaDelimitedList",
            "Default": "us-west-2a, us-west-2b, us-west-2c"
        },
        "DbSubnetIpBlocks": {
            "Type": "CommaDelimitedList",
            "Default": "172.16.0.0/26, 172.16.0.64/26, 172.16.0.128/26"
        }
    },
    "Resources": {
        "DbSubnet1": {
            "Type": "AWS::EC2::Subnet",
            "Properties": {
                "AvailabilityZone": {
                    "Fn::Select": [
                      0,
                      { 
                        "Ref": "VpcAzs" 
                      }
                   ]
                },
                "VpcId": {
                    "Ref": "VPC"
                },
                "CidrBlock": {
                    "Fn::Select": [
                        0,
                        { "Ref": "DbSubnetIpBlocks" }
                    ]
                }
            }
        },
        "DbSubnet2": {
            "Type": "AWS::EC2::Subnet",
            "Properties": {
                "AvailabilityZone": {
                    "Fn::Sub": [
                        "${AWS::Region}${AZ}",
                        {
                            "AZ": {
                                "Fn::Select": [
                                    1,
                                    { "Ref": "VpcAzs" }
                                ]
                            }
                        }
                    ]
                },
                "VpcId": {
                    "Ref": "VPC"
                },
                "CidrBlock": {
                    "Fn::Select": [
                        1,
                        { "Ref": "DbSubnetIpBlocks" }
                    ]
                }
            }
        },
        "DbSubnet3": {
            "Type": "AWS::EC2::Subnet",
            "Properties": {
                "AvailabilityZone": {
                    "Fn::Sub": [
                        "${AWS::Region}${AZ}",
                        {
                            "AZ": {
                                "Fn::Select": [
                                    2,
                                    { "Ref": "VpcAzs" }
                                ]
                            }
                        }
                    ]
                },
                "VpcId": {
                    "Ref": "VPC"
                },
                "CidrBlock": {
                    "Fn::Select": [
                        2,
                        { "Ref": "DbSubnetIpBlocks" }
                    ]
                }
            }
        }
    }
}
```

#### YAML
<a name="parameters-section-structure-example-5.yaml"></a>

```
Parameters:
  VPC:
    Type: String
    Default: vpc-123456
  VpcAzs:
    Type: CommaDelimitedList
    Default: us-west-2a, us-west-2b, us-west-2c
  DbSubnetIpBlocks:
    Type: CommaDelimitedList
    Default: 172.16.0.0/26, 172.16.0.64/26, 172.16.0.128/26
Resources:
  DbSubnet1:
    Type: AWS::EC2::Subnet
    Properties:
      AvailabilityZone: !Select
        - 0 
        - !Ref VpcAzs
      VpcId: !Ref VPC
      CidrBlock: !Select
        - 0
        - !Ref DbSubnetIpBlocks
  DbSubnet2:
    Type: AWS::EC2::Subnet
    Properties:
      AvailabilityZone: !Sub
        - ${AWS::Region}${AZ}
        - AZ: !Select
            - 1
            - !Ref VpcAzs
      VpcId: !Ref VPC
      CidrBlock: !Select
        - 1
        - !Ref DbSubnetIpBlocks
  DbSubnet3:
    Type: AWS::EC2::Subnet
    Properties:
      AvailabilityZone: !Sub
        - ${AWS::Region}${AZ}
        - AZ: !Select
            - 2
            - !Ref VpcAzs
      VpcId: !Ref VPC
      CidrBlock: !Select
        - 2
        - !Ref DbSubnetIpBlocks
```

## 관련 리소스
<a name="parameters-section-structure-related-resources"></a>

또한 CloudFormation은 동적 참조를 사용하여 속성값을 동적으로 지정할 수 있도록 지원합니다. 예를 들어, Systems Manager Parameter Store에 저장되는 보안 문자열을 참조해야 할 수 있습니다. 자세한 내용은 [동적 참조를 사용하여 다른 서비스에 저장된 값 가져오기](dynamic-references.md) 섹션을 참조하세요.

`Ref` 또는 `Sub` 함수 내에서 가상 파라미터를 사용하여 값을 동적으로 채울 수도 있습니다. 자세한 내용은 [가상 파라미터를 사용하여 AWS 값 가져오기](pseudo-parameter-reference.md) 섹션을 참조하세요.

# CloudFormation 템플릿 Outputs 구문
<a name="outputs-section-structure"></a>

선택 사항인 `Outputs` 섹션은 스택의 출력 값을 선언합니다. 이러한 출력 값은 다양한 방식으로 사용할 수 있습니다.
+ **리소스 관련 중요한 세부 정보 수집** - 출력은 리소스 관련 중요 정보를 편리하게 수집할 수 있는 방법입니다. 예를 들면 스택의 S3 버킷 이름을 출력하면 버킷을 보다 쉽게 찾을 수 있습니다. CloudFormation 콘솔의 **출력** 탭이나 [describe-stacks](service_code_examples.md#describe-stacks-sdk) CLI 명령을 사용하여 출력 값을 볼 수 있습니다.
+ **교차 스택 참조** - 출력 값을 다른 스택으로 가져와서 [교차 스택 참조를 생성](using-cfn-stack-exports.md)할 수 있습니다. 이는 여러 스택에서 리소스 또는 구성을 공유해야 할 때 유용합니다.

**중요**  
CloudFormation은 `Outputs` 섹션에 포함한 정보를 삭제하거나 난독화하지 않습니다. 이 섹션을 사용하여 암호나 보안 암호와 같은 민감한 정보를 출력하지 않는 것이 좋습니다.  
출력값은 스택 작업이 완료된 후에 사용할 수 있습니다. 스택 상태가 `IN_PROGRESS` [상태](view-stack-events.md#cfn-console-view-stack-data-resources-status-codes) 중 하나일 때는 스택 출력 값을 사용할 수 없습니다. 출력값을 항상 사용할 수 있는 것은 아니므로 서비스 런타임과 스택 출력값 간에 종속성을 설정하지 않는 것이 좋습니다.

## 구문
<a name="outputs-section-syntax"></a>

`Outputs` 섹션은 키 이름 `Outputs`로 이루어집니다. 템플릿 안에 최대 60개 출력을 선언할 수 있습니다.

다음 예제에서는 `Outputs` 섹션의 구조를 보여줍니다.

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

모든 출력 선언을 괄호 안에 포함합니다. 출력이 여러 개인 경우 쉼표로 구분합니다.

```
"Outputs" : {
  "OutputLogicalID" : {
    "Description" : "Information about the value",
    "Value" : "Value to return",
    "Export" : {
      "Name" : "Name of resource to export"
    }
  }
}
```

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

```
Outputs:
  OutputLogicalID:
    Description: Information about the value
    Value: Value to return
    Export:
      Name: Name of resource to export
```

### 출력 필드
<a name="outputs-section-structure-output-fields"></a>

`Outputs` 섹션은 다음 필드를 포함할 수 있습니다.

**논리적 ID(**논리명이라고도 함)**  
현재 출력의 식별자입니다. 논리적 ID는 영숫자(`a–z`, `A–Z`, `0–9`)여야 하며 템플릿 내에서 고유해야 합니다.

**`Description` (선택 사항)**  
출력값을 설명하는 `String` 유형입니다. 설명 선언 값은 0\$11023바이트 길이의 리터럴 문자열이어야 합니다. 파라미터나 함수를 사용하여 설명을 지정할 수 없습니다.

**`Value`(필수)**  
[describe-stacks](service_code_examples.md#describe-stacks-sdk) 명령에 의해 반환되는 속성의 값입니다. 출력의 값에는 리터럴, 파라미터 참조, 가상 파라미터, 매핑 값 또는 내장 함수가 포함될 수 있습니다.

**`Export` (선택 사항)**  
교차 스택 참조를 위해 내보낼 리소스 출력의 이름입니다.  
내장 함수를 사용하여 내보내기의 `Name` 값을 사용자 지정할 수 있습니다.  
자세한 내용은 [배포된 CloudFormation 스택에서 내보낸 출력 가져오기](using-cfn-stack-exports.md) 섹션을 참조하세요.

출력과 조건을 연결하려면 템플릿의 [Conditions](conditions-section-structure.md) 섹션에 조건을 정의합니다.

## 예제
<a name="outputs-section-structure-examples"></a>

다음 예제에서는 스택 출력의 작동 방식을 보여줍니다.

**Topics**
+ [

### 스택 출력
](#outputs-section-structure-examples-stack-output)
+ [

### `Fn::Sub`를 사용하여 내보내기 이름 사용자 지정
](#outputs-section-structure-examples-cross-stack)
+ [

### `Fn::Join`를 사용하여 내보내기 이름 사용자 지정
](#outputs-section-structure-examples-join-export-name)
+ [

### `Fn::Join`을 사용하여 구성된 URL 반환
](#outputs-section-structure-examples-join-export-url)

### 스택 출력
<a name="outputs-section-structure-examples-stack-output"></a>

다음 예제에서는 `BackupLoadBalancerDNSName` 이름의 출력이 `BackupLoadBalancer` 조건이 true일 때만 논리적 ID가 `CreateProdResources`인 리소스의 DNS 이름을 반환합니다. 이름이 `InstanceID`인 출력은 논리적 ID `EC2Instance`와 함께 EC2 인스턴스의 ID를 반환합니다.

#### JSON
<a name="outputs-section-structure-example.json"></a>

```
"Outputs" : {
  "BackupLoadBalancerDNSName" : {
    "Description": "The DNSName of the backup load balancer",  
    "Value" : { "Fn::GetAtt" : [ "BackupLoadBalancer", "DNSName" ]},
    "Condition" : "CreateProdResources"
  },
  "InstanceID" : {
    "Description": "The Instance ID",  
    "Value" : { "Ref" : "EC2Instance" }
  }
}
```

#### YAML
<a name="outputs-section-structure-example.yaml"></a>

```
Outputs:
  BackupLoadBalancerDNSName:
    Description: The DNSName of the backup load balancer
    Value: !GetAtt BackupLoadBalancer.DNSName
    Condition: CreateProdResources
  InstanceID:
    Description: The Instance ID
    Value: !Ref EC2Instance
```

### `Fn::Sub`를 사용하여 내보내기 이름 사용자 지정
<a name="outputs-section-structure-examples-cross-stack"></a>

다음 예제에서는 `StackVPC`는 VPC의 ID를 반환하고 나서, 스택 이름에 추가된 `VPCID` 이름을 사용하여 교차 스택 참조 값을 내보냅니다.

#### JSON
<a name="outputs-section-structure-cross-stack-example.json"></a>

```
"Outputs" : {
  "StackVPC" : {
    "Description" : "The ID of the VPC",
    "Value" : { "Ref" : "MyVPC" },
    "Export" : {
      "Name" : {"Fn::Sub": "${AWS::StackName}-VPCID" }
    }
  }
}
```

#### YAML
<a name="outputs-section-structure-cross-stack-example.yaml"></a>

```
Outputs:
  StackVPC:
    Description: The ID of the VPC
    Value: !Ref MyVPC
    Export:
      Name: !Sub "${AWS::StackName}-VPCID"
```

`Fn::Sub` 함수에 대한 자세한 내용은 [https://docs.aws.amazon.com/AWSCloudFormation/latest/TemplateReference/intrinsic-function-reference-sub.html](https://docs.aws.amazon.com/AWSCloudFormation/latest/TemplateReference/intrinsic-function-reference-sub.html) 단원을 참조하십시오.

### `Fn::Join`를 사용하여 내보내기 이름 사용자 지정
<a name="outputs-section-structure-examples-join-export-name"></a>

또한 `Fn::Join` 함수를 사용하여 파라미터, 리소스 속성 및 기타 문자열을 기반으로 값을 구성할 수 있습니다.

다음 예제에서는 `Fn::Sub` 함수 대신 `Fn::Join` 함수를 사용하여 내보내기 이름을 사용자 지정합니다. 예제 `Fn::Join` 함수는 콜론을 구분자로 사용하여 스택 이름과 이름 `VPCID`를 연결합니다.

#### JSON
<a name="outputs-section-structure-join-export-name-example.json"></a>

```
"Outputs" : {
  "StackVPC" : {
    "Description" : "The ID of the VPC",
    "Value" : { "Ref" : "MyVPC" },
    "Export" : {
      "Name" : { "Fn::Join" : [ ":", [ { "Ref" : "AWS::StackName" }, "VPCID" ] ] }
    }
  }
}
```

#### YAML
<a name="outputs-section-structure-join-export-name-example.yaml"></a>

```
Outputs:
  StackVPC:
    Description: The ID of the VPC
    Value: !Ref MyVPC
    Export:
      Name: !Join [ ":", [ !Ref "AWS::StackName", VPCID ] ]
```

`Fn::Join` 함수에 대한 자세한 내용은 [https://docs.aws.amazon.com/AWSCloudFormation/latest/TemplateReference/intrinsic-function-reference-join.html](https://docs.aws.amazon.com/AWSCloudFormation/latest/TemplateReference/intrinsic-function-reference-join.html) 단원을 참조하십시오.

### `Fn::Join`을 사용하여 구성된 URL 반환
<a name="outputs-section-structure-examples-join-export-url"></a>

WordPress 사이트를 생성하는 템플릿에 대한 이전 예제에서 `InstallURL`은 `Fn::Join` 함수 호출에서 반환된 문자열로, `http://`, 리소스 `ElasticLoadBalancer`의 DNS 이름, `/wp-admin/install.php`를 연결합니다. 출력 값은 다음과 비슷합니다.

```
http://mywptests-elasticl-1gb51l6sl8y5v-206169572.aws-region.elb.amazonaws.com/wp-admin/install.php
```

#### JSON
<a name="outputs-section-structure-examples-join-export-url.json"></a>

```
{
    "Outputs": {
        "InstallURL": {
            "Value": {
                "Fn::Join": [
                    "",
                    [
                        "http://",
                        {
                            "Fn::GetAtt": [
                                "ElasticLoadBalancer",
                                "DNSName"
                            ]
                        },
                        "/wp-admin/install.php"
                    ]
                ]
            },
            "Description": "Installation URL of the WordPress website"
        }
    }
}
```

#### YAML
<a name="outputs-section-structure-examples-join-export-url.yaml"></a>

```
Outputs:
  InstallURL:
    Value: !Join 
      - ''
      - - 'http://'
        - !GetAtt 
          - ElasticLoadBalancer
          - DNSName
        - /wp-admin/install.php
    Description: Installation URL of the WordPress website
```

`Fn::Join` 함수에 대한 자세한 내용은 [https://docs.aws.amazon.com/AWSCloudFormation/latest/TemplateReference/intrinsic-function-reference-join.html](https://docs.aws.amazon.com/AWSCloudFormation/latest/TemplateReference/intrinsic-function-reference-join.html) 단원을 참조하십시오.

# CloudFormation 템플릿 Mappings 구문
<a name="mappings-section-structure"></a>

선택 사항인 `Mappings` 섹션을 사용하면 특정 조건이나 종속성을 기반으로 값을 지정하는 데 사용할 수 있는 키-값 페어를 만들 수 있습니다.

`Mappings` 섹션의 일반적인 사용 사례 중 하나는 스택이 배포된 AWS 리전을 기반으로 값을 설정하는 것입니다. `AWS::Region` 가상 파라미터를 사용하여 설정할 수 있습니다. `AWS::Region` 가상 파라미터는 CloudFormation에서 스택이 생성되는 리전으로 확인되는 값입니다. 가상 파라미터는 스택 생성 시 CloudFormation에서 확인됩니다.

맵에서 값을 검색하려면 템플릿의 `Resources` 섹션 내에서 `Fn::FindInMap` 내장 함수를 사용하면 됩니다.

## 구문
<a name="mappings-section-structure-syntax"></a>

`Mappings` 섹션에서는 다음 구문을 사용합니다.

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

```
"Mappings" : {
  "MappingLogicalName" : {
    "Key1" : {
      "Name" : "Value1"
    },
    "Key2" : {
      "Name" : "Value2"
    },
    "Key3" : {
      "Name" : "Value3"
    }
  }
}
```

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

```
Mappings: 
  MappingLogicalName: 
    Key1: 
      Name: Value1
    Key2: 
      Name: Value2
    Key3: 
      Name: Value3
```
+ `MappingLogicalName`은 매핑의 논리명입니다.
+ 매핑 내에서 각 맵은 키이며, 그 뒤에는 다른 매핑이 이어집니다.
+ 키는 이름-값 페어의 맵이어야 하며 매핑 내에서 고유해야 합니다.
+ 이름-값 페어는 레이블과, 매핑할 값입니다. 값에 이름을 지정하여 두 개 이상의 값 세트를 키로 매핑할 수 있습니다.
+ 매핑의 키는 문자열이어야 합니다.
+ 값은 `String` 또는 `List` 유형이 될 수 있습니다.

**참고**  
`Mappings` 섹션에는 파라미터, 가상 파라미터 또는 내장 함수를 포함할 수 없습니다.  
매핑의 값이 현재 스택에서 사용되지 않는 경우, 매핑만 업데이트할 수는 없습니다. 리소스를 추가, 수정 또는 삭제하는 변경 내용을 포함해야 합니다.

## 예제
<a name="mappings-section-structure-examples"></a>

**Topics**
+ [

### 기본 매핑
](#mappings-section-structure-basic-example)
+ [

### 여러 값을 사용하여 매핑
](#mappings-section-structure-multiple-values-example)
+ [

### 매핑에서 값 반환
](#mappings-section-structure-return-value-example)
+ [

### 입력 파라미터 및 `Fn::FindInMap`
](#mappings-section-structure-input-parameter-example)

### 기본 매핑
<a name="mappings-section-structure-basic-example"></a>

다음 예제에서는 `Mappings` 맵을 사용하는 `RegionToInstanceType` 매핑을 보여줍니다. 이 매핑에는 단일 문자열 값을 포함하는 이름-값 페어로 매핑된 다섯 개 키가 들어 있습니다. 키는 리전 이름입니다. 각 이름-값 페어는 키로 표현되는 리전에서 사용할 수 있는 T 패밀리의 인스턴스 유형입니다. 이름-값 페어에는 이름(이 예제에서는 `InstanceType`)과 값이 지정됩니다.

#### JSON
<a name="mappings-section-structure-basic-example.json"></a>

```
"Mappings" : {
  "RegionToInstanceType" : {
    "us-east-1"      : { "InstanceType" : "t2.micro" },
    "us-west-1"      : { "InstanceType" : "t2.micro" },
    "eu-west-1"      : { "InstanceType" : "t2.micro" },
    "eu-north-1"     : { "InstanceType" : "t3.micro" },
    "me-south-1"     : { "InstanceType" : "t3.micro" }
  }
}
```

#### YAML
<a name="mappings-section-structure-basic-example.yaml"></a>

```
Mappings:
  RegionToInstanceType:
    us-east-1:
      InstanceType: t2.micro
    us-west-1:
      InstanceType: t2.micro
    eu-west-1:
      InstanceType: t2.micro
    eu-north-1:
      InstanceType: t3.micro
    me-south-1:
      InstanceType: t3.micro
```

### 여러 값을 사용하여 매핑
<a name="mappings-section-structure-multiple-values-example"></a>

다음 예제에는 `MyAMI1` 및 `MyAMI2`, 이렇게 두 가지 값 세트로 매핑되는 리전 키가 있습니다.

**참고**  
이 예제에 표시된 AMI ID는 데모용 자리 표시자입니다. 가능하면 `Mappings` 섹션의 대안으로 AWS Systems Manager 파라미터에 대한 동적 참조를 사용하는 것이 좋습니다. 사용하려는 AMI가 변경될 때마다 모든 템플릿을 새 ID로 업데이트하지 않으려면 스택이 생성되거나 업데이트될 때 AWS Systems Manager 파라미터를 사용하여 최신 AMI ID를 검색하세요. 일반적으로 사용되는 AMI의 최신 버전도 Systems Manager의 퍼블릭 파라미터로 사용할 수 있습니다. 자세한 내용은 [동적 참조를 사용하여 다른 서비스에 저장된 값 가져오기](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/dynamic-references.html)를 참조하세요.

#### JSON
<a name="mappings-section-structure-multiple-values-example"></a>

```
"Mappings" : {
  "RegionToAMI" : {
    "us-east-1"        : { "MyAMI1" : "ami-12345678901234567", "MyAMI2" : "ami-23456789012345678" },
    "us-west-1"        : { "MyAMI1" : "ami-34567890123456789", "MyAMI2" : "ami-45678901234567890" },
    "eu-west-1"        : { "MyAMI1" : "ami-56789012345678901", "MyAMI2" : "ami-67890123456789012" },
    "ap-southeast-1"   : { "MyAMI1" : "ami-78901234567890123", "MyAMI2" : "ami-89012345678901234" },
    "ap-northeast-1"   : { "MyAMI1" : "ami-90123456789012345", "MyAMI2" : "ami-01234567890123456" }
  }
}
```

#### YAML
<a name="mappings-section-structure-multiple-values-example.yaml"></a>

```
Mappings:
  RegionToAMI:
    us-east-1:
      MyAMI1: ami-12345678901234567
      MyAMI2: ami-23456789012345678
    us-west-1:
      MyAMI1: ami-34567890123456789
      MyAMI2: ami-45678901234567890
    eu-west-1:
      MyAMI1: ami-56789012345678901
      MyAMI2: ami-67890123456789012
    ap-southeast-1:
      MyAMI1: ami-78901234567890123
      MyAMI2: ami-89012345678901234
    ap-northeast-1:
      MyAMI1: ami-90123456789012345
      MyAMI2: ami-01234567890123456
```

### 매핑에서 값 반환
<a name="mappings-section-structure-return-value-example"></a>

`Fn::FindInMap` 함수를 사용하여 지정한 키에 따라 명명된 값을 반환할 수 있습니다. 다음 예제 템플릿에는 `FindInMap` 함수를 통해 `InstanceType` 속성이 할당된 Amazon EC2 리소스가 포함되어 있습니다. `FindInMap` 함수는 키를 스택이 생성되는 AWS 리전(`AWS::Region` 가상 파라미터 사용)으로 지정하고 `InstanceType`을 매핑할 값 이름으로 지정합니다. `ImageId`는 Systems Manager 파라미터를 사용하여 최신 Amazon Linux 2 AMI를 동적으로 검색합니다. 가상 parameters에 대한 자세한 내용은 [가상 파라미터를 사용하여 AWS 값 가져오기](pseudo-parameter-reference.md) 단원을 참조하십시오.

#### JSON
<a name="mappings-section-structure-return-value-example.json"></a>

```
{
  "AWSTemplateFormatVersion" : "2010-09-09",
  "Mappings" : {
    "RegionToInstanceType" : {
      "us-east-1"      : { "InstanceType" : "t2.micro" },
      "us-west-1"      : { "InstanceType" : "t2.micro" },
      "eu-west-1"      : { "InstanceType" : "t2.micro" },
      "eu-north-1"     : { "InstanceType" : "t3.micro" },
      "me-south-1"     : { "InstanceType" : "t3.micro" }
    }
  },
  "Resources" : {
    "myEC2Instance" : {
      "Type" : "AWS::EC2::Instance",
      "Properties" : {
        "ImageId" : "{{resolve:ssm:/aws/service/ami-amazon-linux-latest/amzn2-ami-hvm-x86_64-gp2}}",
        "InstanceType" : { "Fn::FindInMap" : [ "RegionToInstanceType", { "Ref" : "AWS::Region" }, "InstanceType" ]}
      }
    }
  }
}
```

#### YAML
<a name="mappings-section-structure-return-value-example.yaml"></a>

```
AWSTemplateFormatVersion: 2010-09-09
Mappings: 
  RegionToInstanceType: 
    us-east-1:
      InstanceType: t2.micro
    us-west-1:
      InstanceType: t2.micro
    eu-west-1:
      InstanceType: t2.micro
    eu-north-1:
      InstanceType: t3.micro
    me-south-1:
      InstanceType: t3.micro
Resources: 
  myEC2Instance: 
    Type: AWS::EC2::Instance
    Properties: 
      ImageId: '{{resolve:ssm:/aws/service/ami-amazon-linux-latest/amzn2-ami-hvm-x86_64-gp2}}'
      InstanceType: !FindInMap [RegionToInstanceType, !Ref 'AWS::Region', InstanceType]
```

### 입력 파라미터 및 `Fn::FindInMap`
<a name="mappings-section-structure-input-parameter-example"></a>

다음 예제 템플릿은 여러 매핑을 사용하여 EC2 인스턴스를 생성하는 방법을 보여줍니다. 템플릿은 중첩 매핑을 사용하여 대상 AWS 리전 및 환경 유형(`Dev` 또는 `Prod`)에 따라 적절한 인스턴스 유형과 보안 그룹을 자동으로 선택합니다. 또한 Systems Manager 파라미터를 사용하여 최신 Amazon Linux 2 AMI를 동적으로 검색합니다.

#### JSON
<a name="mappings-section-structure-input-parameter-example.json"></a>

```
{
  "AWSTemplateFormatVersion" : "2010-09-09",
  "Parameters" : {
    "EnvironmentType" : {
      "Description" : "The environment type (Dev or Prod)",
      "Type" : "String",
      "Default" : "Dev",
      "AllowedValues" : [ "Dev", "Prod" ]
    }
  },
  "Mappings" : {
    "RegionAndEnvironmentToInstanceType" : {
      "us-east-1"        : { "Dev" : "t3.micro", "Prod" : "c5.large" },
      "us-west-1"        : { "Dev" : "t2.micro", "Prod" : "m5.large" }
    },
    "RegionAndEnvironmentToSecurityGroup" : {
      "us-east-1"        : { "Dev" : "sg-12345678", "Prod" : "sg-abcdef01" },
      "us-west-1"        : { "Dev" : "sg-ghijkl23", "Prod" : "sg-45678abc" }
    }
  },
  "Resources" : {
    "Ec2Instance" : {
      "Type" : "AWS::EC2::Instance",
      "Properties" : {
        "ImageId" : "{{resolve:ssm:/aws/service/ami-amazon-linux-latest/amzn2-ami-hvm-x86_64-gp2}}",
        "InstanceType" : { "Fn::FindInMap": [ "RegionAndEnvironmentToInstanceType", { "Ref": "AWS::Region" }, { "Ref": "EnvironmentType" } ]},
        "SecurityGroupIds" : [{ "Fn::FindInMap" : [ "RegionAndEnvironmentToSecurityGroup", { "Ref" : "AWS::Region" }, { "Ref" : "EnvironmentType" } ]}]
      }
    }
  }
}
```

#### YAML
<a name="mappings-section-structure-input-parameter-example.yaml"></a>

```
AWSTemplateFormatVersion: 2010-09-09
Parameters:
  EnvironmentType: 
    Description: The environment type (Dev or Prod)
    Type: String
    Default: Dev
    AllowedValues: 
      - Dev
      - Prod
Mappings:
  RegionAndEnvironmentToInstanceType:
    us-east-1: 
      Dev: t3.micro
      Prod: c5.large
    us-west-1: 
      Dev: t2.micro
      Prod: m5.large
  RegionAndEnvironmentToSecurityGroup: 
    us-east-1: 
      Dev: sg-12345678
      Prod: sg-abcdef01
    us-west-1: 
      Dev: sg-ghijkl23
      Prod: sg-45678abc
Resources:
  Ec2Instance:
    Type: AWS::EC2::Instance
    Properties:
      ImageId: '{{resolve:ssm:/aws/service/ami-amazon-linux-latest/amzn2-ami-hvm-x86_64-gp2}}'
      InstanceType: !FindInMap [RegionAndEnvironmentToInstanceType, !Ref 'AWS::Region', !Ref EnvironmentType]
      SecurityGroupIds:
        - !FindInMap [RegionAndEnvironmentToSecurityGroup, !Ref 'AWS::Region', !Ref EnvironmentType]
```

## 관련 리소스
<a name="mappings-section-related-resources"></a>

이러한 관련 주제는 `Fn::FindInMap` 함수를 사용하는 템플릿을 개발할 때 도움이 될 수 있습니다.
+ [https://docs.aws.amazon.com/AWSCloudFormation/latest/TemplateReference/intrinsic-function-reference-findinmap.html](https://docs.aws.amazon.com/AWSCloudFormation/latest/TemplateReference/intrinsic-function-reference-findinmap.html)
+ [Fn::FindInMap 기능 향상](https://docs.aws.amazon.com/AWSCloudFormation/latest/TemplateReference/intrinsic-function-reference-findinmap-enhancements.html)
+ [https://docs.aws.amazon.com/AWSCloudFormation/latest/TemplateReference/intrinsic-function-reference-sub.html](https://docs.aws.amazon.com/AWSCloudFormation/latest/TemplateReference/intrinsic-function-reference-sub.html)

# CloudFormation 템플릿 Metadata 구문
<a name="metadata-section-structure"></a>

`Metadata`는 JSON 또는 YAML 객체를 사용하여 추가 정보를 저장합니다. 템플릿에서 사용할 수 있는 템플릿 수준 메타데이터 유형은 다음과 같습니다.

사용자 지정 메타데이터  
사용자 정의 키-값 페어를 저장합니다. 예를 들어 리소스 생성에는 영향을 미치지 않지만 인프라, 팀 또는 배포 세부 사항에 대한 추가 컨텍스트를 제시하는 추가 정보를 제공할 수 있습니다.

`AWS::CloudFormation::Interface`  
CloudFormation 콘솔에 표시되는 입력 파라미터의 그룹화 및 순서를 정의합니다. 기본적으로 CloudFormation 콘솔에는 파라미터가 논리적 ID에 따라 영문자순으로 정렬됩니다.

`AWS::CloudFormation::Designer`  
CloudFormation Designer(Designer)는 2025년 2월 5일 수명이 종료되었습니다.



**중요**  
스택 업데이트 중에는 `Metadata` 섹션을 자체적으로 업데이트할 수 없습니다. 리소스를 추가, 수정 또는 삭제하는 변경 내용을 포함할 때만 업데이트할 수 있습니다.  
CloudFormation은 `Metadata` 섹션에 포함된 정보를 변환, 수정 또는 삭제하지 않습니다. 이러한 이유 때문에 이 섹션을 사용하여 암호나 보안 암호와 같은 민감한 정보를 저장하지 않는 것이 좋습니다.

## 구문
<a name="metadata-section-structure-syntax"></a>

CloudFormation 템플릿에서 사용자 지정 메타데이터를 선언하려면 다음 구문을 사용합니다.

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

```
"Metadata" : {
  "Instances" : {"Description" : "Information about the instances"},
  "Databases" : {"Description" : "Information about the databases"}
}
```

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

```
Metadata:
  Instances:
    Description: "Information about the instances"
  Databases: 
    Description: "Information about the databases"
```

`AWS::CloudFormation::Interface`에 대한 구문은 [`AWS::CloudFormation::Interface` 메타데이터를 사용하여 CloudFormation 파라미터 구성](aws-cloudformation-interface.md) 섹션을 참조하세요.

# `AWS::CloudFormation::Interface` 메타데이터를 사용하여 CloudFormation 파라미터 구성
<a name="aws-cloudformation-interface"></a>

`AWS::CloudFormation::Interface`는 CloudFormation 콘솔에서 파라미터가 그룹화되고 정렬되는 방식을 정의하는 메타데이터 키입니다. 기본적으로 콘솔에서 스택을 생성하거나 업데이트하면 콘솔에는 입력 파라미터가 논리적 ID를 기준으로 사전순으로 나열됩니다. 이 키를 사용하면 사용자가 파라미터 값을 효율적으로 지정할 수 있도록 고유의 파라미터 그룹화 및 정렬을 정의할 수 있습니다. 예를 들어, 모든 EC2 관련 파라미터를 한 그룹으로 그룹화하고 모든 VPC 관련 파라미터를 다른 한 그룹으로 그룹화할 수 있습니다.

메타데이터 키에서는 생성할 그룹, 각 그룹에 포함할 파라미터, 그리고 콘솔에서 그룹 내 각 파라미터를 표시하는 순서를 지정할 수 있습니다.

파라미터의 레이블을 정의할 수도 있습니다. 레이블은 파라미터의 논리적 ID 대신 콘솔에 표시되는 표시 이름 또는 설명입니다. 레이블은 사용자가 각 파라미터에 지정할 값을 이해하도록 돕는 데 유용합니다. 예를 들어, `KeyPair` 파라미터에 `Select an EC2 key pair`라는 레이블을 지정할 수 있습니다.

메타데이터 키에서 참조하는 모든 파라미터는 템플릿의 `Parameters` 섹션에 선언해야 합니다.

**참고**  
CloudFormation 콘솔만 `AWS::CloudFormation::Interface` 메타데이터 키를 사용합니다. AWS CLI 및 API 호출은 이 키를 사용하지 않습니다.

## 구문
<a name="aws-resource-cloudformation-interface-syntax"></a>

CloudFormation 템플릿에서 이 객체를 선언하려면 다음 구문을 사용합니다.

### JSON
<a name="aws-resource-cloudformation-interface-syntax.json"></a>

```
"Metadata" : {
  "AWS::CloudFormation::Interface" : {
    "ParameterGroups": [
      {
        "Label": {
          "default": "Group Label"
        },
        "Parameters": [
          "Parameter1",
          "Parameter2"
        ]
      }
    ],
    "ParameterLabels": {
      "Parameter1": {
        "default": "Friendly Name for Parameter1"
      }
    }
  }
}
```

### YAML
<a name="aws-resource-cloudformation-interface-syntax.yaml"></a>

```
Metadata:
  AWS::CloudFormation::Interface:
    ParameterGroups:
      - Label:
          default: Group Label
        Parameters:
          - Parameter1
          - Parameter2
    ParameterLabels:
      Parameter1:
        default: Friendly Name for Parameter1
```

## 속성
<a name="w2aac11c23c29c17c17"></a>

`ParameterGroups`  
그룹 이름, 각 그룹의 파라미터 및 파라미터가 표시되는 순서를 지정하는 파라미터 그룹 유형의 목록입니다.  
*필수 항목 여부*: 아니요    
`Label`  
파라미터 그룹의 이름입니다.  
*필수 항목 여부*: 아니요  
`default`  
CloudFormation 콘솔이 파라미터 그룹의 이름을 지정하는 데 사용하는 기본 레이블입니다.  
*필수 항목 여부*: 아니요  
*유형*: 문자열  
`Parameters`  
그룹에 포함할 파라미터 논리적 ID(대/소문자 구분)의 목록입니다. 파라미터가 템플릿의 `Parameters` 섹션에 이미 정의되어 있어야 합니다. 파라미터는 한 파라미터 그룹에만 포함될 수 있습니다.  
`Other parameters` 그룹에서 파라미터 그룹과 연결되지 않은 파라미터가 사전 순으로 콘솔에 나열됩니다.  
*필수 항목 여부*: 아니요  
*유형*: 문자열 값의 목록

`ParameterLabels`  
스택을 생성하거나 업데이트할 때 CloudFormation 콘솔에 표시되는 파라미터 및 해당 표시 이름의 매핑입니다.  
*필수 항목 여부*: 아니요    
파라미터 레이블  
파라미터에 대한 레이블입니다. 이 레이블은 스택 생성 또는 업데이트 시 CloudFormation 콘솔이 [**파라미터 지정(Specify Parameters)**] 페이지에 표시하는 기억하기 쉬운 이름 또는 설명을 정의합니다. 파라미터 라벨은 템플릿의 `Parameters` 섹션에서 선언된 유효한 파라미터의 논리적 ID(대/소문자 구분)여야 합니다.  
*필수 항목 여부*: 아니요  
`default`  
CloudFormation 콘솔이 파라미터의 이름을 지정하는 데 사용하는 기본 레이블입니다.  
*필수 항목 여부*: 아니요  
*유형*: 문자열

## 예제
<a name="w2aac11c23c29c17c19"></a>

다음 예제에서는 `Network Configuration` 및 `Amazon EC2 Configuration`이라는 두 개의 파라미터 그룹을 정의합니다. `Network Configuration` 그룹에는 템플릿(표시되지 않음)의 `VPCID` 섹션에서 정의되는 `SubnetId`, `SecurityGroupID` 및 `Parameters` 파라미터가 포함됩니다. 이러한 파라미터가 콘솔에 표시되는 순서는 `VPCID` 파라미터로 시작하여 파라미터가 나열되는 순서에 따라 정의됩니다. 예제에서는 비슷한 방식으로 `Amazon EC2 Configuration` 파라미터를 그룹화하고 정렬합니다.

예제에서는 `VPCID` 파라미터의 레이블도 정의합니다. 콘솔에서 파라미터의 논리적 ID(`VPCID`) 대신 **Which VPC should this be deployed to?(어떤 VPC에 배포합니까?)**가 표시됩니다.

### JSON
<a name="aws-cloudformation-interface-example.json"></a>

```
"Metadata" : {
  "AWS::CloudFormation::Interface" : {
    "ParameterGroups" : [
      {
        "Label" : { "default" : "Network Configuration" },
        "Parameters" : [ "VPCID", "SubnetId", "SecurityGroupID" ]
      },
      {
        "Label" : { "default":"Amazon EC2 Configuration" },
        "Parameters" : [ "InstanceType", "KeyName" ]
      }
    ],
    "ParameterLabels" : {
      "VPCID" : { "default" : "Which VPC should this be deployed to?" }
    }
  }
}
```

### YAML
<a name="aws-cloudformation-interface-example.yaml"></a>

```
Metadata: 
  AWS::CloudFormation::Interface: 
    ParameterGroups: 
      - Label: 
          default: "Network Configuration"
        Parameters: 
          - VPCID
          - SubnetId
          - SecurityGroupID
      - Label: 
          default: "Amazon EC2 Configuration"
        Parameters: 
          - InstanceType
          - KeyName
    ParameterLabels: 
      VPCID: 
        default: "Which VPC should this be deployed to?"
```

### 콘솔의 파라미터 그룹
<a name="w2aac11c23c29c17c19c11"></a>

다음 그림에서는 이 예제의 메타데이터 키를 사용하여 스택을 생성하거나 업데이트할 때 파라미터 그룹이 콘솔에 표시되는 방식을 보여 줍니다. **콘솔의 파라미터 그룹** 

![\[이 예제의 파라미터 그룹이 표시된 콘솔입니다.\]](http://docs.aws.amazon.com/ko_kr/AWSCloudFormation/latest/UserGuide/images/console-create-stack-parameter-groups.png)


# CloudFormation 템플릿 Rules 구문
<a name="rules-section-structure"></a>

`Rules` 섹션은 사용자 지정 검증 로직을 활성화하는 CloudFormation 템플릿의 선택 사항 부분입니다. 포함된 경우 이 섹션에는 CloudFormation에서 리소스를 생성하거나 업데이트하기 전에 파라미터 값을 검증하는 규칙 함수가 포함되어 있습니다.

규칙은 표준 파라미터 제약 조건이 충분하지 않은 경우에 유용합니다. 예를 들어 SSL이 활성화된 경우 인증서와 도메인 이름을 모두 제공해야 합니다. 규칙을 통해 이러한 종속성이 충족되도록 보장할 수 있습니다.

## 구문
<a name="template-constraint-rules-syntax"></a>

`Rules` 섹션에서는 다음 구문을 사용합니다.

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

템플릿의 `Rules` 섹션은 키 이름 `Rules`와 그 뒤에 이어지는 콜론 하나로 구성됩니다. 모든 규칙 선언을 괄호로 묶어야 합니다. 규칙을 여러 개 선언할 경우 쉼표로 구분됩니다. 각 규칙에 대해 인용 부호 안의 논리적 이름과 그 뒤에 오는 콜론, 그리고 규칙 조건과 어설션을 묶는 중괄호를 선언합니다.

```
{
    "Rules": {
        "LogicalRuleName1": {
            "RuleCondition": {
                "rule-specific intrinsic function": "Value"
            },
            "Assertions": [
                {
                    "Assert": {
                        "rule-specific intrinsic function": "Value"
                    },
                    "AssertDescription": "Information about this assert"
                },
                {
                    "Assert": {
                        "rule-specific intrinsic function": "Value"
                    },
                    "AssertDescription": "Information about this assert"
                }
            ]
        },
        "LogicalRuleName2": {
            "Assertions": [
                {
                    "Assert": {
                        "rule-specific intrinsic function": "Value"
                    },
                    "AssertDescription": "Information about this assert"
                }
            ]
        }
    }
}
```

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

```
Rules:
  LogicalRuleName1:
    RuleCondition:
      rule-specific intrinsic function: Value
    Assertions:
      - Assert:
          rule-specific intrinsic function: Value
        AssertDescription: Information about this assert
      - Assert:
          rule-specific intrinsic function: Value
        AssertDescription: Information about this assert
  LogicalRuleName2:
    Assertions:
      - Assert:
          rule-specific intrinsic function: Value
        AssertDescription: Information about this assert
```

### 규칙 필드
<a name="rules-section-fields"></a>

`Rules` 섹션은 다음 필드를 포함할 수 있습니다.

**논리적 ID(**논리명이라고도 함)**  
각 규칙의 고유 식별자입니다.

**`RuleCondition` (선택 사항)**  
규칙이 언제 적용될지 결정하는 속성입니다. 규칙 조건을 정의하지 않은 경우, 규칙의 어설션이 항상 적용됩니다. 각 규칙은 하나의 규칙 조건만 정의할 수 있습니다.

**`Assertions`(필수)**  
특정 파라미터에 대해 허용되는 값을 지정하는 하나 이상의 문입니다.

**`Assert`**  
반드시 `true`로 평가되는 조건입니다.

**`AssertDescription`**  
어설션 실패 시 표시되는 메시지입니다.

## 규칙별 내장 함수
<a name="rules-specific-intrinsic-section-structure"></a>

규칙을 정의하려면 템플릿의 `Rules` 섹션에서만 사용할 수 있는 함수인 *규칙 관련 함수*를 사용해야 합니다. 이러한 함수는 중첩될 수 있지만, 규칙 조건 또는 어설션의 최종 결과가 `true`이거나 `false`이어야 합니다.

다음과 같은 규칙 함수를 사용할 수 있습니다.
+ [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-rules.html#fn-contains](https://docs.aws.amazon.com/AWSCloudFormation/latest/TemplateReference/intrinsic-function-reference-rules.html#fn-contains)
+ [https://docs.aws.amazon.com/AWSCloudFormation/latest/TemplateReference/intrinsic-function-reference-rules.html#fn-eachmemberequals](https://docs.aws.amazon.com/AWSCloudFormation/latest/TemplateReference/intrinsic-function-reference-rules.html#fn-eachmemberequals)
+ [https://docs.aws.amazon.com/AWSCloudFormation/latest/TemplateReference/intrinsic-function-reference-rules.html#fn-eachmemberin](https://docs.aws.amazon.com/AWSCloudFormation/latest/TemplateReference/intrinsic-function-reference-rules.html#fn-eachmemberin)
+ [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-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)
+ [https://docs.aws.amazon.com/AWSCloudFormation/latest/TemplateReference/intrinsic-function-reference-rules.html#fn-refall](https://docs.aws.amazon.com/AWSCloudFormation/latest/TemplateReference/intrinsic-function-reference-rules.html#fn-refall)
+ [https://docs.aws.amazon.com/AWSCloudFormation/latest/TemplateReference/intrinsic-function-reference-rules.html#fn-valueof](https://docs.aws.amazon.com/AWSCloudFormation/latest/TemplateReference/intrinsic-function-reference-rules.html#fn-valueof)
+ [https://docs.aws.amazon.com/AWSCloudFormation/latest/TemplateReference/intrinsic-function-reference-rules.html#fn-valueofall](https://docs.aws.amazon.com/AWSCloudFormation/latest/TemplateReference/intrinsic-function-reference-rules.html#fn-valueofall)

이러한 함수는 규칙의 조건 또는 어설션에서 사용합니다. 이 조건 속성은 CloudFormation이 어설션을 적용할지 여부를 결정합니다. 조건이 `true`로 평가되면 CloudFormation은 프로비저닝된 제품이 생성되거나 업데이트될 때 파라미터 값이 유효한지 여부를 확인하기 위해 어설션을 평가합니다. 파라미터 값이 유효하지 않으면 CloudFormation은 스택을 생성하거나 업데이트하지 않습니다. 조건이 `false`로 평가되면 CloudFormation은 파라미터 값을 확인하지 않고 스택 작업을 진행합니다.

## 예제
<a name="template-constraint-rules-example"></a>

**Topics**
+ [

### 조건부로 파라미터 값 확인
](#template-constraint-rules-example-verify)
+ [

### 파라미터 간 검증
](#template-cross-parameter-rules-example)

### 조건부로 파라미터 값 확인
<a name="template-constraint-rules-example-verify"></a>

다음 예제에서는 규칙 두 개가 `InstanceType` 파라미터의 값을 검사합니다. 환경 파라미터(`test` 또는 `prod`)의 값에 따라 사용자는 `InstanceType` 파라미터에 대해 `t3.medium` 또는 `t3.large`를 지정해야 합니다. `InstanceType` 및 `Environment` 파라미터는 동일한 템플릿의 `Parameters` 섹션에서 선언해야 합니다.

#### JSON
<a name="rules-section-example-conditionally-verify.json"></a>

```
{
  "Rules": {
    "testInstanceType": {
      "RuleCondition": {
        "Fn::Equals": [
          {"Ref": "Environment"},
          "test"
        ]
      },
      "Assertions": [
        {
          "Assert": {
            "Fn::Contains": [
              ["t3.medium"],
              {"Ref": "InstanceType"}
            ]
          },
          "AssertDescription": "For a test environment, the instance type must be t3.medium"
        }
      ]
    },
    "prodInstanceType": {
      "RuleCondition": {
        "Fn::Equals": [
          {"Ref": "Environment"},
          "prod"
        ]
      },
      "Assertions": [
        {
          "Assert": {
            "Fn::Contains": [
              ["t3.large"],
              {"Ref": "InstanceType"}
            ]
          },
          "AssertDescription": "For a production environment, the instance type must be t3.large"
        }
      ]
    }
  }
}
```

#### YAML
<a name="rules-section-example-conditionally-verify.yaml"></a>

```
Rules:
  testInstanceType:
    RuleCondition: !Equals 
      - !Ref Environment
      - test
    Assertions:
      - Assert:
          'Fn::Contains':
            - - t3.medium
            - !Ref InstanceType
        AssertDescription: 'For a test environment, the instance type must be t3.medium'
  prodInstanceType:
    RuleCondition: !Equals 
      - !Ref Environment
      - prod
    Assertions:
      - Assert:
          'Fn::Contains':
            - - t3.large
            - !Ref InstanceType
        AssertDescription: 'For a production environment, the instance type must be t3.large'
```

### 파라미터 간 검증
<a name="template-cross-parameter-rules-example"></a>

다음 샘플 템플릿은 파라미터 간 검증을 위한 규칙의 사용을 보여줍니다. 이는 로드 밸런서 뒤의 Auto Scaling 그룹에서 실행되는 샘플 웹 사이트를 생성합니다. 웹 사이트는 입력 파라미터에 따라 포트 80 또는 443에서 사용할 수 있습니다. Auto Scaling 그룹의 인스턴스가 모든 포트(기본값 8888)에서 수신되도록 구성할 수 있습니다.

이 템플릿의 규칙은 스택 생성 전에 입력 파라미터를 검증합니다. 모든 서브넷이 지정된 VPC에 속하는지 검증하고 `UseSSL` 파라미터가 `Yes`로 설정된 경우, SSL 인증서 ARN과 호스팅 영역 이름이 모두 제공되는지 확인합니다.

**참고**  
이 템플릿에서 스택을 생성할 경우 사용한 AWS 리소스에 대한 요금이 청구됩니다.

#### JSON
<a name="rules-section-example-cross-parameter-validation.json"></a>

```
{
  "AWSTemplateFormatVersion": "2010-09-09",
  "Parameters": {
    "VpcId": {
      "Type": "AWS::EC2::VPC::Id",
      "Description": "VpcId of your existing Virtual Private Cloud (VPC)",
      "ConstraintDescription": "must be the VPC Id of an existing Virtual Private Cloud."
    },
    "Subnets": {
      "Type": "List<AWS::EC2::Subnet::Id>",
      "Description": "The list of SubnetIds in your Virtual Private Cloud (VPC)",
      "ConstraintDescription": "must be a list of at least two existing subnets associated with at least two different availability zones."
    },
    "InstanceType": {
      "Description": "WebServer EC2 instance type",
      "Type": "String",
      "Default": "t2.micro",
      "AllowedValues": ["t2.micro", "t3.micro"],
      "ConstraintDescription": "must be a valid EC2 instance type."
    },
    "KeyName": {
      "Description": "Name of an existing EC2 KeyPair to enable SSH access to the instances",
      "Type": "AWS::EC2::KeyPair::KeyName",
      "ConstraintDescription": "must be the name of an existing EC2 KeyPair."
    },
    "SSHLocation": {
      "Description": "The IP address range that can be used to SSH to the EC2 instances",
      "Type": "String",
      "MinLength": "9",
      "MaxLength": "18",
      "Default": "0.0.0.0/0",
      "AllowedPattern": "(\\d{1,3})\\.(\\d{1,3})\\.(\\d{1,3})\\.(\\d{1,3})/(\\d{1,2})",
      "ConstraintDescription": "must be a valid IP CIDR range of the form x.x.x.x/x."
    },
    "UseSSL": {
      "AllowedValues": ["Yes", "No"],
      "Default": "No",
      "Description": "Select \"Yes\" to implement SSL, \"No\" to skip (default).",
      "Type": "String"
    },
    "ALBSSLCertificateARN": {
      "Default": "",
      "Description": "[Optional] The ARN of the SSL certificate to be used for the Application Load Balancer",
      "Type": "String"
    },
    "HostedZoneName": {
      "AllowedPattern": "^$|(([a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9\\-]*[a-zA-Z0-9])\\.)*([A-Za-z0-9]|[A-Za-z0-9][A-Za-z0-9\\-]*[A-Za-z0-9])$",
      "Default": "",
      "Description": "[Optional] The domain name of a valid Hosted Zone on AWS.",
      "Type": "String"
    }
  },
  "Conditions": {
    "UseALBSSL": {"Fn::Equals": [{"Ref": "UseSSL"}, "Yes"]}
  },
  "Rules": {
    "SubnetsInVPC": {
      "Assertions": [
        {
          "Assert": {"Fn::EachMemberEquals": [{"Fn::ValueOf": ["Subnets", "VpcId"]}, {"Ref": "VpcId"}]},
          "AssertDescription": "All subnets must be in the VPC"
        }
      ]
    },
    "ValidateHostedZone": {
      "RuleCondition": {"Fn::Equals": [{"Ref": "UseSSL"}, "Yes"]},
      "Assertions": [
        {
          "Assert": {"Fn::Not": [{"Fn::Equals": [{"Ref": "ALBSSLCertificateARN"}, ""]}]},
          "AssertDescription": "ACM Certificate value cannot be empty if SSL is required"
        },
        {
          "Assert": {"Fn::Not": [{"Fn::Equals": [{"Ref": "HostedZoneName"}, ""]}]},
          "AssertDescription": "Route53 Hosted Zone Name is mandatory when SSL is required"
        }
      ]
    }
  },
  "Resources": {
    "WebServerGroup": {
      "Type": "AWS::AutoScaling::AutoScalingGroup",
      "Properties": {
        "VPCZoneIdentifier": {"Ref": "Subnets"},
        "LaunchTemplate": {
          "LaunchTemplateId": {"Ref": "LaunchTemplate"},
          "Version": {"Fn::GetAtt": ["LaunchTemplate","LatestVersionNumber"]}
        },
        "MinSize": "2",
        "MaxSize": "2",
        "TargetGroupARNs": [{"Ref": "ALBTargetGroup"}]
      },
      "CreationPolicy": {
        "ResourceSignal": {"Timeout": "PT15M"}
      },
      "UpdatePolicy": {
        "AutoScalingRollingUpdate": {
          "MinInstancesInService": "1",
          "MaxBatchSize": "1",
          "PauseTime": "PT15M",
          "WaitOnResourceSignals": true
        }
      }
    },
    "LaunchTemplate": {
      "Type": "AWS::EC2::LaunchTemplate",
      "Metadata": {
        "Comment": "Install a simple application",
        "AWS::CloudFormation::Init": {
          "config": {
            "packages": {"yum": {"httpd": []}},
            "files": {
              "/var/www/html/index.html": {
                "content": {"Fn::Join": ["\n", ["<h1>Congratulations, you have successfully launched the AWS CloudFormation sample.</h1>"]]},
                "mode": "000644",
                "owner": "root",
                "group": "root"
              },
              "/etc/cfn/cfn-hup.conf": {
                "content": {"Fn::Join": ["", [
                  "[main]\n",
                  "stack=", {"Ref": "AWS::StackId"}, "\n",
                  "region=", {"Ref": "AWS::Region"}, "\n"
                ]]},
                "mode": "000400",
                "owner": "root",
                "group": "root"
              },
              "/etc/cfn/hooks.d/cfn-auto-reloader.conf": {
                "content": {"Fn::Join": ["", [
                  "[cfn-auto-reloader-hook]\n",
                  "triggers=post.update\n",
                  "path=Resources.LaunchTemplate.Metadata.AWS::CloudFormation::Init\n",
                  "action=/opt/aws/bin/cfn-init -v ",
                  "         --stack ", {"Ref": "AWS::StackName"},
                  "         --resource LaunchTemplate ",
                  "         --region ", {"Ref": "AWS::Region"}, "\n",
                  "runas=root\n"
                ]]},
                "mode": "000400",
                "owner": "root",
                "group": "root"
              }
            },
            "services": {
              "sysvinit": {
                "httpd": {
                  "enabled": "true",
                  "ensureRunning": "true"
                },
                "cfn-hup": {
                  "enabled": "true",
                  "ensureRunning": "true",
                  "files": [
                    "/etc/cfn/cfn-hup.conf",
                    "/etc/cfn/hooks.d/cfn-auto-reloader.conf"
                  ]
                }
              }
            }
          }
        }
      },
      "Properties": {
        "LaunchTemplateName": {"Fn::Sub": "${AWS::StackName}-launch-template"},
        "LaunchTemplateData": {
          "ImageId": "{{resolve:ssm:/aws/service/ami-amazon-linux-latest/amzn2-ami-hvm-x86_64-gp2}}",
          "SecurityGroupIds": [{"Ref": "InstanceSecurityGroup"}],
          "InstanceType": {"Ref": "InstanceType"},
          "KeyName": {"Ref": "KeyName"},
          "UserData": {
            "Fn::Base64": {"Fn::Join": ["", [
              "#!/bin/bash\n",
              "yum install -y aws-cfn-bootstrap\n",
              "/opt/aws/bin/cfn-init -v ",
              "         --stack ", {"Ref": "AWS::StackName"},
              "         --resource LaunchTemplate ",
              "         --region ", {"Ref": "AWS::Region"}, "\n",
              "/opt/aws/bin/cfn-signal -e $? ",
              "         --stack ", {"Ref": "AWS::StackName"},
              "         --resource WebServerGroup ",
              "         --region ", {"Ref": "AWS::Region"}, "\n"
            ]]}
          }
        }
      }
    },
    "ELBSecurityGroup": {
      "Type": "AWS::EC2::SecurityGroup",
      "Properties": {
        "GroupDescription": "Allow access to the ELB",
        "VpcId": {"Ref": "VpcId"},
        "SecurityGroupIngress": [{
          "Fn::If": [
            "UseALBSSL",
            {
              "IpProtocol": "tcp",
              "FromPort": 443,
              "ToPort": 443,
              "CidrIp": "0.0.0.0/0"
            },
            {
              "IpProtocol": "tcp",
              "FromPort": 80,
              "ToPort": 80,
              "CidrIp": "0.0.0.0/0"
            }
          ]
        }]
      }
    },
    "ApplicationLoadBalancer": {
      "Type": "AWS::ElasticLoadBalancingV2::LoadBalancer",
      "Properties": {
        "Subnets": {"Ref": "Subnets"},
        "SecurityGroups": [{"Ref": "ELBSecurityGroup"}]
      }
    },
    "ALBListener": {
      "Type": "AWS::ElasticLoadBalancingV2::Listener",
      "Properties": {
        "DefaultActions": [{
          "Type": "forward",
          "TargetGroupArn": {"Ref": "ALBTargetGroup"}
        }],
        "LoadBalancerArn": {"Ref": "ApplicationLoadBalancer"},
        "Port": {"Fn::If": ["UseALBSSL", 443, 80]},
        "Protocol": {"Fn::If": ["UseALBSSL", "HTTPS", "HTTP"]},
        "Certificates": [{
          "Fn::If": [
            "UseALBSSL",
            {"CertificateArn": {"Ref": "ALBSSLCertificateARN"}},
            {"Ref": "AWS::NoValue"}
          ]
        }]
      }
    },
    "ALBTargetGroup": {
      "Type": "AWS::ElasticLoadBalancingV2::TargetGroup",
      "Properties": {
        "HealthCheckIntervalSeconds": 30,
        "HealthCheckTimeoutSeconds": 5,
        "HealthyThresholdCount": 3,
        "Port": 80,
        "Protocol": "HTTP",
        "UnhealthyThresholdCount": 5,
        "VpcId": {"Ref": "VpcId"}
      }
    },
    "InstanceSecurityGroup": {
      "Type": "AWS::EC2::SecurityGroup",
      "Properties": {
        "GroupDescription": "Enable SSH access and HTTP access on the inbound port",
        "SecurityGroupIngress": [
          {
            "IpProtocol": "tcp",
            "FromPort": 80,
            "ToPort": 80,
            "SourceSecurityGroupId": {"Fn::Select": [0, {"Fn::GetAtt": ["ApplicationLoadBalancer", "SecurityGroups"]}]}
          },
          {
            "IpProtocol": "tcp",
            "FromPort": 22,
            "ToPort": 22,
            "CidrIp": {"Ref": "SSHLocation"}
          }
        ],
        "VpcId": {"Ref": "VpcId"}
      }
    },
    "RecordSet": {
      "Type": "AWS::Route53::RecordSetGroup",
      "Condition": "UseALBSSL",
      "Properties": {
        "HostedZoneName": {"Fn::Join": ["", [{"Ref": "HostedZoneName"}, "."]]},
        "RecordSets": [{
          "Name": {"Fn::Join": ["", [
            {"Fn::Select": ["0", {"Fn::Split": [".", {"Fn::GetAtt": ["ApplicationLoadBalancer", "DNSName"]}]}]},
            ".",
            {"Ref": "HostedZoneName"},
            "."
          ]]},
          "Type": "A",
          "AliasTarget": {
            "DNSName": {"Fn::GetAtt": ["ApplicationLoadBalancer", "DNSName"]},
            "EvaluateTargetHealth": true,
            "HostedZoneId": {"Fn::GetAtt": ["ApplicationLoadBalancer", "CanonicalHostedZoneID"]}
          }
        }]
      }
    }
  },
  "Outputs": {
    "URL": {
      "Description": "URL of the website",
      "Value": {"Fn::Join": ["", [
        {"Fn::If": [
          "UseALBSSL",
          {"Fn::Join": ["", [
            "https://",
            {"Fn::Join": ["", [
              {"Fn::Select": ["0", {"Fn::Split": [".", {"Fn::GetAtt": ["ApplicationLoadBalancer", "DNSName"]}]}]},
              ".",
              {"Ref": "HostedZoneName"},
              "."
            ]]}
          ]]},
          {"Fn::Join": ["", [
            "http://",
            {"Fn::GetAtt": ["ApplicationLoadBalancer", "DNSName"]}
          ]]}
        ]}
      ]]}
    }
  }
}
```

#### YAML
<a name="rules-section-example-syntax.yaml"></a>

```
AWSTemplateFormatVersion: 2010-09-09
Parameters:
  VpcId:
    Type: AWS::EC2::VPC::Id
    Description: VpcId of your existing Virtual Private Cloud (VPC)
    ConstraintDescription: must be the VPC Id of an existing Virtual Private Cloud.
  Subnets:
    Type: List<AWS::EC2::Subnet::Id>
    Description: The list of SubnetIds in your Virtual Private Cloud (VPC)
    ConstraintDescription: >-
      must be a list of at least two existing subnets associated with at least
      two different availability zones. They should be residing in the selected
      Virtual Private Cloud.
  InstanceType:
    Description: WebServer EC2 instance type
    Type: String
    Default: t2.micro
    AllowedValues:
      - t2.micro
      - t3.micro
    ConstraintDescription: must be a valid EC2 instance type.
  KeyName:
    Description: Name of an existing EC2 KeyPair to enable SSH access to the instances
    Type: AWS::EC2::KeyPair::KeyName
    ConstraintDescription: must be the name of an existing EC2 KeyPair.
  SSHLocation:
    Description: The IP address range that can be used to SSH to the EC2 instances
    Type: String
    MinLength: '9'
    MaxLength: '18'
    Default: 0.0.0.0/0
    AllowedPattern: '(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})/(\d{1,2})'
    ConstraintDescription: must be a valid IP CIDR range of the form x.x.x.x/x.
  UseSSL:
    AllowedValues:
      - 'Yes'
      - 'No'
    ConstraintDescription: Select Yes to create a HTTPS Listener
    Default: 'No'
    Description: 'Select "Yes" to implement SSL, "No" to skip (default).'
    Type: String
  ALBSSLCertificateARN:
    Default: ''
    Description: >-
      [Optional] The ARN of the SSL certificate to be used for the Application
      Load Balancer
    Type: String
  HostedZoneName:
    AllowedPattern: >-
      ^$|(([a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9\-]*[a-zA-Z0-9])\.)*([A-Za-z0-9]|[A-Za-z0-9][A-Za-z0-9\-]*[A-Za-z0-9])$
    Default: ''
    Description: '[Optional] The domain name of a valid Hosted Zone on AWS.'
    Type: String
Conditions:
  UseALBSSL: !Equals 
    - !Ref UseSSL
    - 'Yes'
Rules:
  SubnetsInVPC:
    Assertions:
      - Assert:
          'Fn::EachMemberEquals':
            - 'Fn::ValueOf':
                - Subnets
                - VpcId
            - Ref: VpcId
        AssertDescription: All subnets must be in the VPC
  ValidateHostedZone:
    RuleCondition: !Equals 
      - !Ref UseSSL
      - 'Yes'
    Assertions:
      - Assert: !Not 
          - !Equals 
            - !Ref ALBSSLCertificateARN
            - ''
        AssertDescription: ACM Certificate value cannot be empty if SSL is required
      - Assert: !Not 
          - !Equals 
            - !Ref HostedZoneName
            - ''
        AssertDescription: Route53 Hosted Zone Name is mandatory when SSL is required
Resources:
  WebServerGroup:
    Type: AWS::AutoScaling::AutoScalingGroup
    Properties:
      VPCZoneIdentifier: !Ref Subnets
      LaunchTemplate:
        LaunchTemplateId: !Ref LaunchTemplate
        Version: !GetAtt LaunchTemplate.LatestVersionNumber
      MinSize: '2'
      MaxSize: '2'
      TargetGroupARNs:
        - !Ref ALBTargetGroup
    CreationPolicy:
      ResourceSignal:
        Timeout: PT15M
    UpdatePolicy:
      AutoScalingRollingUpdate:
        MinInstancesInService: '1'
        MaxBatchSize: '1'
        PauseTime: PT15M
        WaitOnResourceSignals: 'true'
  LaunchTemplate:
    Type: AWS::EC2::LaunchTemplate
    Metadata:
      Comment: Install a simple application
      AWS::CloudFormation::Init:
        config:
          packages:
            yum:
              httpd: []
          files:
            /var/www/html/index.html:
              content: !Join 
                - |+
                - - >-
                    <h1>Congratulations, you have successfully launched the AWS
                    CloudFormation sample.</h1>
              mode: '000644'
              owner: root
              group: root
            /etc/cfn/cfn-hup.conf:
              content: !Sub |
                [main]
                stack=${AWS::StackId}
                region=${AWS::Region}
              mode: '000400'
              owner: root
              group: root
            /etc/cfn/hooks.d/cfn-auto-reloader.conf:
              content: !Sub |-
                [cfn-auto-reloader-hook]
                triggers=post.update
                path=Resources.LaunchTemplate.Metadata.AWS::CloudFormation::Init
                action=/opt/aws/bin/cfn-init -v --stack ${AWS::StackName} --resource LaunchTemplate --region ${AWS::Region}
                runas=root
              mode: '000400'
              owner: root
              group: root
          services:
            sysvinit:
              httpd:
                enabled: 'true'
                ensureRunning: 'true'
              cfn-hup:
                enabled: 'true'
                ensureRunning: 'true'
                files:
                  - /etc/cfn/cfn-hup.conf
                  - /etc/cfn/hooks.d/cfn-auto-reloader.conf
    Properties:
      LaunchTemplateName: !Sub ${AWS::StackName}-launch-template
      LaunchTemplateData:
        ImageId: '{{resolve:ssm:/aws/service/ami-amazon-linux-latest/amzn2-ami-hvm-x86_64-gp2}}'
        SecurityGroupIds:
        - !Ref InstanceSecurityGroup
        InstanceType: !Ref InstanceType
        KeyName: !Ref KeyName
        UserData: !Base64
          Fn::Sub: |
            #!/bin/bash
            yum install -y aws-cfn-bootstrap
            /opt/aws/bin/cfn-init -v --stack ${AWS::StackName} --resource LaunchTemplate --region ${AWS::Region}
            /opt/aws/bin/cfn-signal -e $? --stack ${AWS::StackName} --resource WebServerGroup --region ${AWS::Region}
  ELBSecurityGroup:
    Type: AWS::EC2::SecurityGroup
    Properties:
      GroupDescription: Allow access to the ELB
      VpcId: !Ref VpcId
      SecurityGroupIngress:
        - !If 
          - UseALBSSL
          - IpProtocol: tcp
            FromPort: 443
            ToPort: 443
            CidrIp: 0.0.0.0/0
          - IpProtocol: tcp
            FromPort: 80
            ToPort: 80
            CidrIp: 0.0.0.0/0
  ApplicationLoadBalancer:
    Type: AWS::ElasticLoadBalancingV2::LoadBalancer
    Properties:
      Subnets: !Ref Subnets
      SecurityGroups:
        - !Ref ELBSecurityGroup
  ALBListener:
    Type: AWS::ElasticLoadBalancingV2::Listener
    Properties:
      DefaultActions:
        - Type: forward
          TargetGroupArn: !Ref ALBTargetGroup
      LoadBalancerArn: !Ref ApplicationLoadBalancer
      Port: !If
        - UseALBSSL
        - 443
        - 80
      Protocol: !If 
        - UseALBSSL
        - HTTPS
        - HTTP
      Certificates:
        - !If 
          - UseALBSSL
          - CertificateArn: !Ref ALBSSLCertificateARN
          - !Ref 'AWS::NoValue'
  ALBTargetGroup:
    Type: AWS::ElasticLoadBalancingV2::TargetGroup
    Properties:
      HealthCheckIntervalSeconds: 30
      HealthCheckTimeoutSeconds: 5
      HealthyThresholdCount: 3
      Port: 80
      Protocol: HTTP
      UnhealthyThresholdCount: 5
      VpcId: !Ref VpcId
  InstanceSecurityGroup:
    Type: AWS::EC2::SecurityGroup
    Properties:
      GroupDescription: Enable SSH access and HTTP access on the inbound port
      SecurityGroupIngress:
        - IpProtocol: tcp
          FromPort: 80
          ToPort: 80
          SourceSecurityGroupId: !Select 
            - 0
            - !GetAtt 
              - ApplicationLoadBalancer
              - SecurityGroups
        - IpProtocol: tcp
          FromPort: 22
          ToPort: 22
          CidrIp: !Ref SSHLocation
      VpcId: !Ref VpcId
  RecordSet:
    Type: AWS::Route53::RecordSetGroup
    Condition: UseALBSSL
    Properties:
      HostedZoneName: !Join 
        - ''
        - - !Ref HostedZoneName
          - .
      RecordSets:
        - Name: !Join 
            - ''
            - - !Select 
                - '0'
                - !Split 
                  - .
                  - !GetAtt 
                    - ApplicationLoadBalancer
                    - DNSName
              - .
              - !Ref HostedZoneName
              - .
          Type: A
          AliasTarget:
            DNSName: !GetAtt 
              - ApplicationLoadBalancer
              - DNSName
            EvaluateTargetHealth: true
            HostedZoneId: !GetAtt 
              - ApplicationLoadBalancer
              - CanonicalHostedZoneID
Outputs:
  URL:
    Description: URL of the website
    Value: !Join 
      - ''
      - - !If 
          - UseALBSSL
          - !Join 
            - ''
            - - 'https://'
              - !Join 
                - ''
                - - !Select 
                    - '0'
                    - !Split 
                      - .
                      - !GetAtt 
                        - ApplicationLoadBalancer
                        - DNSName
                  - .
                  - !Ref HostedZoneName
                  - .
          - !Join 
            - ''
            - - 'http://'
              - !GetAtt 
                - ApplicationLoadBalancer
                - DNSName
```

# 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) 주제를 참조하세요.

# CloudFormation 템플릿 Transform 섹션
<a name="transform-section-structure"></a>

선택 사항인 `Transform` 섹션은 CloudFormation에서 템플릿을 어떤 방식으로 처리하는 데 사용하는 하나 이상의 매크로를 지정합니다.

매크로는 텍스트 찾기 및 바꾸기와 같은 간단한 작업을 수행하거나 전체 템플릿을 보다 광범위하게 변환할 수 있습니다. CloudFormation은 지정된 순서에 따라 매크로를 실행합니다. 변경 세트를 생성할 때 CloudFormation에서 처리된 템플릿 콘텐츠를 포함하는 변경 세트를 생성합니다. 변경 사항을 검토하고 변경 세트를 실행할 수 있습니다. 매크로 작동 방식에 대한 자세한 내용은 [템플릿 매크로를 사용하여 CloudFormation 템플릿에서 사용자 지정 처리 수행](template-macros.md) 단원을 참조하세요.

CloudFormation은 CloudFormation에서 호스팅되는 매크로인 **변환도 지원합니다. CloudFormation은 이러한 변환을 실행 순서 및 범위 측면에서 사용자가 생성한 모든 매크로와 동일하게 처리합니다. 자세한 내용은 ​[변환 참조](https://docs.aws.amazon.com/AWSCloudFormation/latest/TemplateReference/transform-reference.html)를 참조하세요.

여러 매크로를 선언하려면 목록 형식을 사용하고 하나 이상의 매크로를 지정합니다.

예를 들어, 아래 템플릿 샘플에서 CloudFormation은 `MyMacro`를 평가하고 `AWS::Serverless`를 평가합니다. 두 가지는 모두 전체 템플릿의 콘텐츠를 처리할 수 있는데, 이는 `Transform` 섹션이 포함되어 있기 때문입니다.

```
# Start of processable content for MyMacro and AWS::Serverless
Transform:
  - MyMacro
  - 'AWS::Serverless'
Resources:
  WaitCondition:
    Type: AWS::CloudFormation::WaitCondition
  MyBucket:
    Type: AWS::S3::Bucket
    Properties: 
      BucketName: amzn-s3-demo-bucket
      Tags: [{"key":"value"}]
      CorsConfiguration: []
  MyEc2Instance:
    Type: AWS::EC2::Instance 
    Properties:
      ImageId: ami-1234567890abcdef0
# End of processable content for MyMacro and AWS::Serverless
```

# CloudFormation 템플릿 형식 버전 구문
<a name="format-version-structure"></a>

`AWSTemplateFormatVersion` 섹션(선택 사항)은 템플릿이 따르는 템플릿 형식 버전을 식별합니다. 최신 템플릿 포맷 버전은 `2010-09-09`이며 현재 유일한 유효 값입니다.

템플릿 포맷 버전은 API 버전과 같지 않습니다. 템플릿 포맷 버전은 API 버전과 상관없이 변경될 수 있습니다.

템플릿 포맷 버전 선언 값은 리터럴 문자열이어야 합니다 파라미터나 함수를 사용하여 템플릿 포맷 버전을 지정할 수 없습니다. 값을 지정하지 않을 경우 CloudFormation에서는 최신 템플릿 포맷 버전이라고 가정합니다. 다음 코드 조각은 템플릿 포맷 버전 선언 예입니다.

## JSON
<a name="format-version-structure-example.json"></a>

```
"AWSTemplateFormatVersion" : "2010-09-09"
```

## YAML
<a name="format-version-structure-example.yaml"></a>

```
AWSTemplateFormatVersion: 2010-09-09
```

# CloudFormation 템플릿 Description 구문
<a name="template-description-structure"></a>

템플릿의 `Description` 섹션(선택 사항)을 사용하면 템플릿을 설명하는 텍스트 문자열을 포함시킬 수 있습니다. 이 섹션은 항상 템플릿 포맷 버전 섹션 다음에 이어져야 합니다.

설명 선언 값은 0 \$1 1023바이트 길이의 리터럴 문자열이어야 합니다. 파라미터나 함수를 사용하여 설명을 지정할 수 없습니다. 다음 코드 조각은 설명 선언을 보여주는 예입니다.

**중요**  
스택 업데이트 중에는 `Description` 섹션을 자체적으로 업데이트할 수 없습니다. 리소스를 추가, 수정 또는 삭제하는 변경 내용을 포함할 때만 업데이트할 수 있습니다.

## JSON
<a name="template-description-structure-example.json"></a>

```
"Description" : "Here are some details about the template."
```

## YAML
<a name="template-description-structure-example.yaml"></a>

```
Description: > Here are some details about the template.
```