Lambda와 CloudFormation 사용

Lambda와 CloudFormation 사용

AWS CloudFormation 템플릿에서 Lambda 함수를 커스텀 리소스(custom resource)의 대상으로 지정할 수 있습니다. 커스텀 리소스는 스택 수명주기 이벤트 중에 파라미터를 처리하거나, 구성 값을 검색하거나, 다른 AWS 서비스를 호출하는 데 사용합니다.

출처: AWS Lambda 개발자 안내서

본문

다음 예제는 템플릿의 다른 곳에 정의된 함수를 호출합니다.

Resources:
  primerinvoke:
    Type: AWS::CloudFormation::CustomResource
    Version: "1.0"
    Properties:
      ServiceToken: !GetAtt primer.Arn
      FunctionName: !Ref randomerror

**서비스 토큰(service token)**은 스택을 만들거나 갱신하거나 삭제할 때 CloudFormation이 호출하는 함수의 Amazon Resource Name(ARN)입니다. FunctionName 같은 추가 속성도 포함할 수 있으며, CloudFormation은 이를 함수에 그대로 전달합니다.

CloudFormation은 콜백 URL이 포함된 이벤트로 Lambda 함수를 비동기적으로 호출합니다.

{
    "RequestType": "Create",
    "ServiceToken": "arn:aws:lambda:us-east-1:123456789012:function:lambda-error-processor-primer-14ROR2T3JKU66",
    "ResponseURL": "https://cloudformation-custom-resource-response-useast1.s3-us-east-1.amazonaws.com/arn%3Aaws%3Acloudformation%3Aus-east-1%3A123456789012%3Astack/lambda-error-processor/1134083a-2608-1e91-9897-022501a2c456%7Cprimerinvoke%7C5d478078-13e9-baf0-464a-7ef285ecc786?AWSAccessKeyId=«redacted:AKIA…»&Expires=1555451971&Signature=28UijZePE5I4dvukKQqM%2F9Rf1o4%3D",
    "StackId": "arn:aws:cloudformation:us-east-1:123456789012:stack/lambda-error-processor/1134083a-2608-1e91-9897-022501a2c456",
    "RequestId": "5d478078-13e9-baf0-464a-7ef285ecc786",
    "LogicalResourceId": "primerinvoke",
    "ResourceType": "AWS::CloudFormation::CustomResource",
    "ResourceProperties": {
        "ServiceToken": "arn:aws:lambda:us-east-1:123456789012:function:lambda-error-processor-primer-14ROR2T3JKU66",
        "FunctionName": "lambda-error-processor-randomerror-ZWUC391MQAJK"
    }
}

함수는 성공 또는 실패를 나타내는 응답을 콜백 URL로 반환할 책임이 있습니다. 전체 응답 구문은 'Custom resource response objects'를 참고하세요.

{
    "Status": "SUCCESS",
    "PhysicalResourceId": "2019/04/18/[$LATEST]b3d1bfc65f19ec610654e4d9b9de47a0",
    "StackId": "arn:aws:cloudformation:us-east-1:123456789012:stack/lambda-error-processor/1134083a-2608-1e91-9897-022501a2c456",
    "RequestId": "5d478078-13e9-baf0-464a-7ef285ecc786",
    "LogicalResourceId": "primerinvoke"
}

CloudFormation은 응답 전송을 처리하는 cfn-response라는 라이브러리를 제공합니다. 템플릿 안에서 함수를 정의한다면 이름으로 라이브러리를 require 할 수 있습니다. 그러면 CloudFormation이 함수용으로 만드는 배포 패키지에 라이브러리를 추가합니다.

커스텀 리소스가 사용하는 함수에 탄력적 네트워크 인터페이스(Elastic Network Interface)가 연결되어 있다면, VPC 정책에 다음 리소스를 추가하세요. 여기서 region은 대시 없이 표기한 함수가 있는 리전입니다. 예를 들어 us-east-1은 useast1입니다. 이렇게 하면 커스텀 리소스가 CloudFormation 스택에 신호를 보내는 콜백 URL에 응답할 수 있습니다.

arn:aws:s3:::cloudformation-custom-resource-response-region",
"arn:aws:s3:::cloudformation-custom-resource-response-region/*",

다음 예제 함수는 두 번째 함수를 호출합니다. 호출이 성공하면 함수는 CloudFormation에 성공 응답을 보내고 스택 갱신이 계속됩니다. 템플릿은 AWS Serverless Application Model이 제공하는 AWS::Serverless::Function 리소스 유형을 사용합니다.

Transform: 'AWS::Serverless-2016-10-31'
Resources:
  primer:
    Type: AWS::Serverless::Function
    Properties:
      Handler: index.handler
      Runtime: nodejs16.x
      InlineCode: |
        var aws = require('aws-sdk');
        var response = require('cfn-response');
        exports.handler = function(event, context) {
            // For Delete requests, immediately send a SUCCESS response.
            if (event.RequestType == "Delete") {
                response.send(event, context, "SUCCESS");
                return;
            }
            var responseStatus = "FAILED";
            var responseData = {};
            var functionName = event.ResourceProperties.FunctionName
            var lambda = new aws.Lambda();
            lambda.invoke({ FunctionName: functionName }, function(err, invokeResult) {
                if (err) {
                    responseData = {Error: "Invoke call failed"};
                    console.log(responseData.Error + ":\n", err);
                }
                else responseStatus = "SUCCESS";
                response.send(event, context, responseStatus, responseData);
            });
        };
      Description: Invoke a function to create a log stream.
      MemorySize: 128
      Timeout: 8
      Role: !GetAtt role.Arn
      Tracing: Active

커스텀 리소스가 호출하는 함수가 템플릿에 정의되어 있지 않다면, AWS CloudFormation User Guide의 cfn-response 모듈에서 cfn-response의 소스 코드를 얻을 수 있습니다.

커스텀 리소스에 대한 자세한 내용은 AWS CloudFormation User Guide의 'Custom resources'를 참고하세요.

더 알아보기 (Learn more)