샘플 템플릿 - AWS CloudFormation

샘플 템플릿

프로덕션, 개발 또는 테스트 스택에 대한 리소스를 조건부로 생성

비슷하지만 약간 조정된 스택을 생성하려는 경우도 있습니다. 예를 들어, 프로덕션 애플리케이션에 사용할 템플릿이 필요할 수 있습니다. 개발 또는 테스트에 사용할 수 있도록 동일한 프로덕션 스택을 생성하려고 합니다. 하지만 개발 및 테스트의 경우 프로덕션 레벨 스택에 포함되는 추가 용량 중 일부가 필요하지 않을 수도 있습니다. 그 대신 다음 예제와 같이 환경 유형 입력 파라미터를 사용하여 프로덕션, 개발 또는 테스트에 특정한 스택 리소스를 조건부로 생성할 수 있습니다.

예 JSON
{ "AWSTemplateFormatVersion" : "2010-09-09", "Mappings" : { "RegionMap" : { "us-east-1" : { "AMI" : "ami-0ff8a91507f77f867"}, "us-west-1" : { "AMI" : "ami-0bdb828fd58c52235"}, "us-west-2" : { "AMI" : "ami-a0cfeed8"}, "eu-west-1" : { "AMI" : "ami-047bb4163c506cd98"}, "sa-east-1" : { "AMI" : "ami-07b14488da8ea02a0"}, "ap-southeast-1" : { "AMI" : "ami-08569b978cc4dfa10"}, "ap-southeast-2" : { "AMI" : "ami-09b42976632b27e9b"}, "ap-northeast-1" : { "AMI" : "ami-06cd52961ce9f0d85"} } }, "Parameters" : { "EnvType" : { "Description" : "Environment type.", "Default" : "test", "Type" : "String", "AllowedValues" : ["prod", "dev", "test"], "ConstraintDescription" : "must specify prod, dev, or test." } }, "Conditions" : { "CreateProdResources" : {"Fn::Equals" : [{"Ref" : "EnvType"}, "prod"]}, "CreateDevResources" : {"Fn::Equals" : [{"Ref" : "EnvType"}, "dev"]} }, "Resources" : { "EC2Instance" : { "Type" : "AWS::EC2::Instance", "Properties" : { "ImageId" : { "Fn::FindInMap" : [ "RegionMap", { "Ref" : "AWS::Region" }, "AMI" ]}, "InstanceType" : { "Fn::If" : [ "CreateProdResources", "c1.xlarge", {"Fn::If" : [ "CreateDevResources", "m1.large", "m1.small" ]} ]} } }, "MountPoint" : { "Type" : "AWS::EC2::VolumeAttachment", "Condition" : "CreateProdResources", "Properties" : { "InstanceId" : { "Ref" : "EC2Instance" }, "VolumeId" : { "Ref" : "NewVolume" }, "Device" : "/dev/sdh" } }, "NewVolume" : { "Type" : "AWS::EC2::Volume", "Condition" : "CreateProdResources", "Properties" : { "Size" : "100", "AvailabilityZone" : { "Fn::GetAtt" : [ "EC2Instance", "AvailabilityZone" ]} } } } }
예 YAML
AWSTemplateFormatVersion: "2010-09-09" Mappings: RegionMap: us-east-1: AMI: "ami-0ff8a91507f77f867" us-west-1: AMI: "ami-0bdb828fd58c52235" us-west-2: AMI: "ami-a0cfeed8" eu-west-1: AMI: "ami-047bb4163c506cd98" sa-east-1: AMI: "ami-07b14488da8ea02a0" ap-southeast-1: AMI: "ami-08569b978cc4dfa10" ap-southeast-2: AMI: "ami-09b42976632b27e9b" ap-northeast-1: AMI: "ami-06cd52961ce9f0d85" Parameters: EnvType: Description: Environment type. Default: test Type: String AllowedValues: [prod, dev, test] ConstraintDescription: must specify prod, dev, or test. Conditions: CreateProdResources: !Equals [!Ref EnvType, prod] CreateDevResources: !Equals [!Ref EnvType, "dev"] Resources: EC2Instance: Type: "AWS::EC2::Instance" Properties: ImageId: !FindInMap [RegionMap, !Ref "AWS::Region", AMI] InstanceType: !If [CreateProdResources, c1.xlarge, !If [CreateDevResources, m1.large, m1.small]] MountPoint: Type: "AWS::EC2::VolumeAttachment" Condition: CreateProdResources Properties: InstanceId: !Ref EC2Instance VolumeId: !Ref NewVolume Device: /dev/sdh NewVolume: Type: "AWS::EC2::Volume" Condition: CreateProdResources Properties: Size: 100 AvailabilityZone: !GetAtt EC2Instance.AvailabilityZone

prod 파라미터에 대해 dev, test 또는 EnvType를 지정할 수 있습니다. 템플릿에서는 환경 유형별로 다른 인스턴스 유형을 지정합니다. 인스턴스 유형은 대용량의 컴퓨팅 최적화된 인스턴스 유형부터 작은 범용 인스턴스 유형까지 다양합니다. 인스턴스 유형을 조건부로 지정하려면 템플릿의 조건 섹션에서 CreateProdResources 조건(EnvType 파라미터 값이 prod와 같으면 true로 평가됨)과 CreateDevResources 조건(파라미터 값이 dev로 평가되면 true로 평가됨)을 정의합니다.

InstanceType 속성에서 템플릿은 두 Fn::If 내장 함수를 중첩하여 사용할 인스턴스 유형을 결정합니다. CreateProdResources 조건이 true이면 인스턴스 유형은 c1.xlarge이고, false이면 CreateDevResources 조건이 평가됩니다. CreateDevResources 조건이 true이면 인스턴스 유형이 m1.large이고, 그렇지 않으면 m1.small입니다.

인스턴스 유형 이외에 프로덕션 환경에서는 Amazon EC2 볼륨을 생성하여 인스턴스에 연결합니다. 조건이 true로 평가되는 경우에만 리소스가 생성되도록 MountPointNewVolume 리소스는 CreateProdResources 조건과 연결됩니다.

조건부로 리소스 속성 할당

이 예에서는 스냅샷에서 Amazon RDS DB 인스턴스를 생성할 수 있습니다. DBSnapshotName 파라미터를 지정한 경우 CloudFormation에서는 DB 인스턴스를 생성할 때 파라미터 값을 스냅샷 이름으로 사용합니다. 기본값(빈 문자열)을 유지할 경우 CloudFormation에서는 DBSnapshotIdentifier 속성을 제거하고 DB 인스턴스를 처음부터 생성합니다.

이 예에서는 NoEcho 속성이 true로 설정된 DBUserDBPassword 파라미터를 정의합니다. NoEcho 속성을 true로 설정한 경우, 아래 지정된 위치에 저장된 정보를 제외하고 CloudFormation은 스택 또는 스택 이벤트를 설명하는 모든 호출에 대해 별표(*****)로 마스킹 처리된 파라미터 값을 반환합니다.

중요

NoEcho 속성을 사용해도 다음에 저장된 정보는 마스킹되지 않습니다.

  • Metadata 템플릿 섹션. CloudFormation은 Metadata 섹션에 포함된 정보를 변환, 수정 또는 삭제하지 않습니다. 자세한 내용은 Metadata 단원을 참조하십시오.

  • Outputs 템플릿 섹션. 자세한 내용은 결과 단원을 참조하십시오.

  • 리소스 정의의 Metadata 속성입니다. 자세한 내용은 Metadata 속성 단원을 참조하십시오.

이러한 메커니즘을 사용하여 암호나 보안 정보와 같은 중요한 정보를 포함하지 않는 것이 좋습니다.

중요

AWS Systems Manager Parameter Store 또는 AWS Secrets Manager와 같이 CloudFormation 외부에서 저장 및 관리되는 중요한 정보를 참조하려면 CloudFormation 템플릿에 직접 중요한 정보를 포함하는 대신 스택 템플릿에 있는 동적 파라미터를 사용하는 것이 좋습니다.

자세한 내용은 템플릿에 자격 증명을 포함하지 않음 모범 사례를 참조하세요.

예 JSON
{ "AWSTemplateFormatVersion" : "2010-09-09", "Parameters": { "DBUser": { "NoEcho": "true", "Description" : "The database admin account username", "Type": "String", "MinLength": "1", "MaxLength": "16", "AllowedPattern" : "[a-zA-Z][a-zA-Z0-9]*", "ConstraintDescription" : "must begin with a letter and contain only alphanumeric characters." }, "DBPassword": { "NoEcho": "true", "Description" : "The database admin account password", "Type": "String", "MinLength": "1", "MaxLength": "41", "AllowedPattern" : "[a-zA-Z0-9]*", "ConstraintDescription" : "must contain only alphanumeric characters." }, "DBSnapshotName": { "Description": "The name of a DB snapshot (optional)", "Default": "", "Type": "String" } }, "Conditions": { "UseDBSnapshot": {"Fn::Not": [{"Fn::Equals" : [{"Ref" : "DBSnapshotName"}, ""]}]} }, "Resources" : { "MyDB" : { "Type" : "AWS::RDS::DBInstance", "Properties" : { "AllocatedStorage" : "5", "DBInstanceClass" : "db.t2.small", "Engine" : "MySQL", "EngineVersion" : "5.5", "MasterUsername" : { "Ref" : "DBUser" }, "MasterUserPassword" : { "Ref" : "DBPassword" }, "DBParameterGroupName" : { "Ref" : "MyRDSParamGroup" }, "DBSnapshotIdentifier" : { "Fn::If" : [ "UseDBSnapshot", {"Ref" : "DBSnapshotName"}, {"Ref" : "AWS::NoValue"} ] } } }, "MyRDSParamGroup" : { "Type": "AWS::RDS::DBParameterGroup", "Properties" : { "Family" : "MySQL5.5", "Description" : "CloudFormation Sample Database Parameter Group", "Parameters" : { "autocommit" : "1" , "general_log" : "1", "old_passwords" : "0" } } } } }
예 YAML
AWSTemplateFormatVersion: "2010-09-09" Parameters: DBUser: NoEcho: true Description: The database admin account username Type: String MinLength: 1 MaxLength: 16 AllowedPattern: "[a-zA-Z][a-zA-Z0-9]*" ConstraintDescription: must begin with a letter and contain only alphanumeric characters. DBPassword: NoEcho: true Description: The database admin account password Type: String MinLength: 1 MaxLength: 41 AllowedPattern: "[a-zA-Z0-9]*" ConstraintDescription: must contain only alphanumeric characters. DBSnapshotName: Description: The name of a DB snapshot (optional) Default: "" Type: String Conditions: UseDBSnapshot: !Not [!Equals [!Ref DBSnapshotName, ""]] Resources: MyDB: Type: "AWS::RDS::DBInstance" Properties: AllocatedStorage: 5 DBInstanceClass: db.t2.small Engine: MySQL EngineVersion: 5.5 MasterUsername: !Ref DBUser MasterUserPassword: !Ref DBPassword DBParameterGroupName: !Ref MyRDSParamGroup DBSnapshotIdentifier: !If [UseDBSnapshot, !Ref DBSnapshotName, !Ref "AWS::NoValue"] MyRDSParamGroup: Type: "AWS::RDS::DBParameterGroup" Properties: Family: MySQL5.5 Description: CloudFormation Sample Database Parameter Group Parameters: autocommit: 1 general_log: 1 old_passwords: 0

UseDBSnapshot 조건이 true로 평가되려면 DBSnapshotName이 빈 문자열이 아니어야 합니다. UseDBSnapshot 조건이 true로 평가되면 CloudFormation에서는 DBSnapshotIdentifier 속성에 대한 DBSnapshotName 파라미터 값을 사용합니다. 조건이 false로 평가되면 CloudFormation이 DBSnapshotIdentifier 속성을 제거합니다. AWS::NoValue 가상 파라미터는 반환 값으로 사용될 경우 해당 리소스 속성을 제거합니다.

조건부로 기존 리소스 사용

이 예제에서는 이미 생성한 Amazon EC2 보안 그룹을 사용하거나 템플릿에 지정된 새 보안 그룹을 생성할 수 있습니다. ExistingSecurityGroup 파라미터의 경우 default 보안 그룹 이름 또는 NONE을 지정할 수 있습니다. default를 지정한 경우 CloudFormation에서는 이미 생성되어 있고 이름이 default인 보안 그룹을 사용합니다. NONE을 지정한 경우 CloudFormation에서는 템플릿에 정의된 보안 그룹을 생성합니다.

예 JSON
{ "Parameters" : { "ExistingSecurityGroup" : { "Description" : "An existing security group ID (optional).", "Default" : "NONE", "Type" : "String", "AllowedValues" : ["default", "NONE"] } }, "Conditions" : { "CreateNewSecurityGroup" : {"Fn::Equals" : [{"Ref" : "ExistingSecurityGroup"}, "NONE"] } }, "Resources" : { "MyInstance" : { "Type" : "AWS::EC2::Instance", "Properties" : { "ImageId" : "ami-0ff8a91507f77f867", "SecurityGroups" : [{ "Fn::If" : [ "CreateNewSecurityGroup", {"Ref" : "NewSecurityGroup"}, {"Ref" : "ExistingSecurityGroup"} ] }] } }, "NewSecurityGroup" : { "Type" : "AWS::EC2::SecurityGroup", "Condition" : "CreateNewSecurityGroup", "Properties" : { "GroupDescription" : "Enable HTTP access via port 80", "SecurityGroupIngress" : [ { "IpProtocol" : "tcp", "FromPort" : 80, "ToPort" : 80, "CidrIp" : "0.0.0.0/0" } ] } } }, "Outputs" : { "SecurityGroupId" : { "Description" : "Group ID of the security group used.", "Value" : { "Fn::If" : [ "CreateNewSecurityGroup", {"Ref" : "NewSecurityGroup"}, {"Ref" : "ExistingSecurityGroup"} ] } } } }
예 YAML
Parameters: ExistingSecurityGroup: Description: An existing security group ID (optional). Default: NONE Type: String AllowedValues: - default - NONE Conditions: CreateNewSecurityGroup: !Equals [!Ref ExistingSecurityGroup, NONE] Resources: MyInstance: Type: "AWS::EC2::Instance" Properties: ImageId: "ami-0ff8a91507f77f867" SecurityGroups: !If [CreateNewSecurityGroup, !Ref NewSecurityGroup, !Ref ExistingSecurityGroup] NewSecurityGroup: Type: "AWS::EC2::SecurityGroup" Condition: CreateNewSecurityGroup Properties: GroupDescription: Enable HTTP access via port 80 SecurityGroupIngress: - IpProtocol: tcp FromPort: 80 ToPort: 80 CidrIp: 0.0.0.0/0 Outputs: SecurityGroupId: Description: Group ID of the security group used. Value: !If [CreateNewSecurityGroup, !Ref NewSecurityGroup, !Ref ExistingSecurityGroup]

NewSecurityGroup 리소스를 생성할지 여부를 결정하기 위해 리소스는 CreateNewSecurityGroup 조건과 연결됩니다. 조건이 true인 경우(ExistingSecurityGroup 파라미터가 NONE과 같은 경우)에만 리소스가 생성됩니다.

SecurityGroups 속성에서 템플릿은 Fn::If 내장 함수를 사용하여 사용할 보안 그룹을 결정합니다. CreateNewSecurityGroup 조건이 true로 평가되면 보안 그룹 속성에서 NewSecurityGroup 리소스를 참조하고, CreateNewSecurityGroup 조건이 false로 평가되면 보안 그룹 속성에서 ExistingSecurityGroup 파라미터(default 보안 그룹)를 참조합니다.

마지막으로 템플릿에서는 보안 그룹 ID를 조건부로 출력합니다. CreateNewSecurityGroup 조건이 true로 평가되면 CloudFormation은 NewSecurityGroup 리소스의 보안 그룹 ID를 출력합니다. 조건이 false이면 CloudFormation은 ExistingSecurityGroup 리소스의 보안 그룹 ID를 출력합니다.