

# CloudFormation 템플릿 코드 조각
<a name="quickref-cloudformation"></a>

**Topics**
+ [중첩 스택](#w2aac11c41c23b5)
+ [대기 조건](#w2aac11c41c23b7)

## 중첩 스택
<a name="w2aac11c41c23b5"></a>

### 템플릿에 스택 중첩
<a name="scenario-stack"></a>

이 예제 템플릿에는 `myStack`이라는 중첩 스택 리소스가 포함되어 있습니다. CloudFormation은 템플릿에서 스택을 생성할 때 `myStack`을 생성하는데, 이 스택에서 템플릿은 `TemplateURL` 속성에 지정됩니다. 출력 값 `StackRef`는 `myStack`의 스택 ID이고 `OutputFromNestedStack` 값은 `myStack` 리소스의 출력 값 `BucketName`을 반환합니다. `Outputs.nestedstackoutputname` 형식은 중첩 스택의 출력 값을 지정하는 용도로 예약되어 있으며 포함 템플릿 내 어디서든 사용할 수 있습니다.

자세한 내용은 [https://docs.aws.amazon.com/AWSCloudFormation/latest/TemplateReference/aws-resource-cloudformation-stack.html](https://docs.aws.amazon.com/AWSCloudFormation/latest/TemplateReference/aws-resource-cloudformation-stack.html) 섹션을 참조하세요.

#### JSON
<a name="quickref-cloudformation-example-1.json"></a>

```
 1. {
 2.     "AWSTemplateFormatVersion" : "2010-09-09",
 3.     "Resources" : {
 4.         "myStack" : {
 5. 	       "Type" : "AWS::CloudFormation::Stack",
 6. 	       "Properties" : {
 7. 	        "TemplateURL" : "https://s3.amazonaws.com/cloudformation-templates-us-east-1/S3_Bucket.template",
 8.               "TimeoutInMinutes" : "60"
 9. 	       }
10.         }
11.     },
12.     "Outputs": {
13.        "StackRef": {"Value": { "Ref" : "myStack"}},
14.        "OutputFromNestedStack" : {
15.              "Value" : { "Fn::GetAtt" : [ "myStack", "Outputs.BucketName" ] }
16.        }
17.     }
18. }
```

#### YAML
<a name="quickref-cloudformation-example-1.yaml"></a>

```
 1. AWSTemplateFormatVersion: '2010-09-09'
 2. Resources:
 3.   myStack:
 4.     Type: AWS::CloudFormation::Stack
 5.     Properties:
 6.       TemplateURL: https://s3.amazonaws.com/cloudformation-templates-us-east-1/S3_Bucket.template
 7.       TimeoutInMinutes: '60'
 8. Outputs:
 9.   StackRef:
10.     Value: !Ref myStack
11.   OutputFromNestedStack:
12.     Value: !GetAtt myStack.Outputs.BucketName
```

### 템플릿 내 입력 파라미터를 사용하여 스택 중첩
<a name="scenario-stack-parameters"></a>

이 예제 템플릿에는 입력 파라미터를 지정하는 스택 리소스가 들어 있습니다. CloudFormation이 템플릿에서 스택을 생성하는 경우, `myStackWithParams` 스택을 생성하는 데 사용되는 템플릿의 입력 파라미터로 `Parameters` 속성 안에 선언되는 값 페어를 사용합니다. 이 예제에는 `InstanceType` 및 `KeyName` 파라미터가 지정되어 있습니다.

자세한 내용은 [https://docs.aws.amazon.com/AWSCloudFormation/latest/TemplateReference/aws-resource-cloudformation-stack.html](https://docs.aws.amazon.com/AWSCloudFormation/latest/TemplateReference/aws-resource-cloudformation-stack.html) 섹션을 참조하세요.

#### JSON
<a name="quickref-cloudformation-example-2.json"></a>

```
 1. {
 2.     "AWSTemplateFormatVersion" : "2010-09-09",
 3.     "Resources" : {
 4.         "myStackWithParams" : {
 5.   	       "Type" : "AWS::CloudFormation::Stack",
 6. 	       "Properties" : {
 7. 	           "TemplateURL" : "https://s3.amazonaws.com/cloudformation-templates-us-east-1/EC2ChooseAMI.template",
 8. 	           "Parameters" : {
 9. 	               "InstanceType" : "t2.micro",
10. 	               "KeyName" : "mykey"
11. 	           }
12.    	       }
13.         }
14.     }
15. }
```

#### YAML
<a name="quickref-cloudformation-example-2.yaml"></a>

```
1. AWSTemplateFormatVersion: '2010-09-09'
2. Resources:
3.   myStackWithParams:
4.     Type: AWS::CloudFormation::Stack
5.     Properties:
6.       TemplateURL: https://s3.amazonaws.com/cloudformation-templates-us-east-1/EC2ChooseAMI.template
7.       Parameters:
8.         InstanceType: t2.micro
9.         KeyName: mykey
```

## 대기 조건
<a name="w2aac11c41c23b7"></a>

### Amazon EC2 인스턴스에 대기 조건 사용
<a name="scenario-waitcondition"></a>

**중요**  
Amazon EC2 및 Auto Scaling 리소스의 경우 대기 조건 대신 CreationPolicy 속성을 사용하는 것이 좋습니다. 그러한 리소스에 CreationPolicy 속성을 추가하고 cfn-signal 헬퍼 스크립트를 사용하여 인스턴스 생성 프로세스가 완료되면 신호를 보내도록 합니다.

생성 정책을 사용할 수 없는 경우 다음 예제 템플릿을 참조할 수 있습니다. 이 템플릿에서는 대기 조건을 사용하여 Amazon EC2 인스턴스를 선언합니다. `myWaitCondition` 대기 조건은 신호 전송에 `myWaitConditionHandle`을 사용하고, `DependsOn` 속성을 사용하여 Amazon EC2 인스턴스 리소스가 생성된 후 대기 조건이 트리거되도록 지정하고, `Timeout` 속성을 사용하여 대기 조건의 기간을 4,500초로 지정합니다. 또한, 대기 조건에 신호를 전송하는 미리 서명된 URL이 `Ec2Instance` 리소스의 `UserData` 속성을 사용하여 Amazon EC2 인스턴스에 전달되므로, 해당 Amazon EC2 인스턴스에서 실행 중인 애플리케이션이나 스크립트에서 미리 서명된 URL을 검색한 후 이 URL을 사용하여 대기 조건에 성공 또는 실패 신호를 전송할 수 있습니다. `cfn-signal`을 사용하거나 대기 조건에 신호를 전송하는 애플리케이션 또는 스크립트를 생성해야 합니다. 출력 값 `ApplicationData`에는 대기 조건 신호에서 다시 전달된 데이터가 포함되어 있습니다.

자세한 내용은 [CloudFormation 템플릿에서 대기 조건 생성](using-cfn-waitcondition.md) 섹션을 참조하세요.

#### JSON
<a name="quickref-cloudformation-example-3.json"></a>

```
 1. {
 2.     "AWSTemplateFormatVersion" : "2010-09-09",
 3.     "Mappings" : {
 4.         "RegionMap" : {
 5.             "us-east-1" : {
 6.                 "AMI" : "ami-0123456789abcdef0"
 7.             },
 8.             "us-west-1" : {
 9.                 "AMI" : "ami-0987654321fedcba0"
10.             },
11.             "eu-west-1" : {
12.                 "AMI" : "ami-0abcdef123456789a"
13.             },
14.             "ap-northeast-1" : {
15.                 "AMI" : "ami-0fedcba987654321b"
16.             },
17.             "ap-southeast-1" : {
18.                 "AMI" : "ami-0c1d2e3f4a5b6c7d8"
19.             }
20.         }
21.     },
22.     "Resources" : {
23.         "Ec2Instance" : {
24.             "Type" : "AWS::EC2::Instance",
25.             "Properties" : {
26.                 "UserData" : { "Fn::Base64" : {"Ref" : "myWaitHandle"}},
27.                 "ImageId" : { "Fn::FindInMap" : [ "RegionMap", { "Ref" : "AWS::Region" }, "AMI" ]}
28.             }
29.         },
30.         "myWaitHandle" : {
31.             "Type" : "AWS::CloudFormation::WaitConditionHandle",
32.             "Properties" : {
33.             }
34.         },
35.         "myWaitCondition" : {
36.             "Type" : "AWS::CloudFormation::WaitCondition",
37.             "DependsOn" : "Ec2Instance",
38.             "Properties" : {
39.                 "Handle" : { "Ref" : "myWaitHandle" },
40.                 "Timeout" : "4500"
41.             }
42.         }
43.     },
44.     "Outputs" : {
45.         "ApplicationData" : {
46.             "Value" : { "Fn::GetAtt" : [ "myWaitCondition", "Data" ]},
47.             "Description" : "The data passed back as part of signalling the WaitCondition."
48.         }
49.     }
50. }
```

#### YAML
<a name="quickref-cloudformation-example-3.yaml"></a>

```
 1. AWSTemplateFormatVersion: '2010-09-09'
 2. Mappings:
 3.   RegionMap:
 4.     us-east-1:
 5.       AMI: ami-0123456789abcdef0
 6.     us-west-1:
 7.       AMI: ami-0987654321fedcba0
 8.     eu-west-1:
 9.       AMI: ami-0abcdef123456789a
10.     ap-northeast-1:
11.       AMI: ami-0fedcba987654321b
12.     ap-southeast-1:
13.       AMI: ami-0c1d2e3f4a5b6c7d8
14. Resources:
15.   Ec2Instance:
16.     Type: AWS::EC2::Instance
17.     Properties:
18.       UserData:
19.         Fn::Base64: !Ref myWaitHandle
20.       ImageId:
21.         Fn::FindInMap:
22.         - RegionMap
23.         - Ref: AWS::Region
24.         - AMI
25.   myWaitHandle:
26.     Type: AWS::CloudFormation::WaitConditionHandle
27.     Properties: {}
28.   myWaitCondition:
29.     Type: AWS::CloudFormation::WaitCondition
30.     DependsOn: Ec2Instance
31.     Properties:
32.       Handle: !Ref myWaitHandle
33.       Timeout: '4500'
34. Outputs:
35.   ApplicationData:
36.     Value: !GetAtt myWaitCondition.Data
37.     Description: The data passed back as part of signalling the WaitCondition.
```

### cfn-signal 헬퍼 스크립트를 사용하여 대기 조건에 신호 전송
<a name="scenario-waitcondition-cfn-signal"></a>

이 예제는 대기 조건에 성공 신호를 전송하는 `cfn-signal` 명령줄을 보여줍니다. EC2 인스턴스의 `UserData` 속성에서 명령줄을 정의해야 합니다.

#### JSON
<a name="w2aac11c41c23b7b4b4"></a>

```
"UserData": {
  "Fn::Base64": {
    "Fn::Join": [
      "", 
      [
         "#!/bin/bash -xe\n",
         "/opt/aws/bin/cfn-signal --exit-code 0 '", 
         {
           "Ref": "myWaitHandle"
         },
         "'\n"
      ]   
    ]
  }
}
```

#### YAML
<a name="w2aac11c41c23b7b4b6"></a>

```
UserData:
  Fn::Base64: !Sub |
    #!/bin/bash -xe
    /opt/aws/bin/cfn-signal --exit-code 0 '${myWaitHandle}'
```

### Curl을 사용하여 대기 조건에 신호 전송
<a name="scenario-waitcondition-curl"></a>

다음 예제에서는 대기 조건에 성공 신호를 전송하는 Curl 명령줄을 보여 줍니다.

```
1. curl -T /tmp/a "https://cloudformation-waitcondition-test.s3.amazonaws.com/arn%3Aaws%3Acloudformation%3Aus-east-1%3A034017226601%3Astack%2Fstack-gosar-20110427004224-test-stack-with-WaitCondition--VEYW%2Fe498ce60-70a1-11e0-81a7-5081d0136786%2FmyWaitConditionHandle?Expires=1303976584&AWSAccessKeyId=AKIAIOSFODNN7EXAMPLE&Signature=ik1twT6hpS4cgNAw7wyOoRejVoo%3D"
```

이때 file /tmp/a에는 다음과 같은 JSON 구조가 포함되어 있습니다.

```
1. {
2.   "Status" : "SUCCESS",
3.   "Reason" : "Configuration Complete",
4.   "UniqueId" : "ID1234",
5.   "Data" : "Application has completed configuration."
6. }
```

이 예제에서는 명령줄에서 JSON을 파라미터로 전송하는 경우를 제외하고는 동일한 성공 신호를 전송하는 Curl 명령줄을 표시합니다.

```
1. curl -X PUT -H 'Content-Type:' --data-binary '{"Status" : "SUCCESS","Reason" : "Configuration Complete","UniqueId" : "ID1234","Data" : "Application has completed configuration."}' "https://cloudformation-waitcondition-test.s3.amazonaws.com/arn%3Aaws%3Acloudformation%3Aus-east-1%3A034017226601%3Astack%2Fstack-gosar-20110427004224-test-stack-with-WaitCondition--VEYW%2Fe498ce60-70a1-11e0-81a7-5081d0136786%2FmyWaitConditionHandle?Expires=1303976584&AWSAccessKeyId=AKIAIOSFODNN7EXAMPLE&Signature=ik1twT6hpS4cgNAw7wyOoRejVoo%3D"
```