IaaS/퍼블릭클라우드

(AWS) CloudFormation에서 Lambda Function 배포하기

armyost 2022. 1. 28. 06:08
728x90

CF에서 Lambda를 배포하는 방법은 다음과 같다. 

 

1. 인라인 방식 : CF Template내에서 Lambda정의하기

템플릿 내에서 Lambda를 정의하는 방법이다. 아래에 보다싶이 Row가 매우 길어진다는 단점이 있다. 

배포는 일반 CF Template배포하듯이 하면된다. 

 

특이한점은 Lambda Function이 생성된후에 Lambda콘솔을 들어가 해당 Lambda Function을 보면 '이 Lambda Function은 CloudFormation Stack에 의해 생성된 것'이라고 표시된다. 

 

Template 사용 예제

Resources: 
	ListBucketsS3Lambda: 
        Type: "AWS::Lambda::Function"
        Properties: 
          Handler: "index.handler"
          Role: 
            Fn::GetAtt: 
              - "LambdaExecutionRole"
              - "Arn"
          Runtime: "python3.7"
          Code: 
            ZipFile: |
              import boto3

              # Create an S3 client
              s3 = boto3.client('s3')

              def handler(event, context):
                # Call S3 to list current buckets
                response = s3.list_buckets()

                # Get a list of all bucket names from the response
                buckets = [bucket['Name'] for bucket in response['Buckets']]

                # Print out the bucket list
                print("Bucket List: %s" % buckets)

                return buckets

 

2. S3에 Lambda 소스를 Zip파일로 올리고 CF Template에서 S3에 저장된 Zip파일을 사용한다.

이 방식의 장점은 Template의 재사용성이 향상된다는 점이다. Lambda Zip소스 S3저장위치를 Parameter로 꺼냄으로써 Template을 돌릴때 다른 Lambda Zip 코드를 적용함으로써 다른 Lambda Function을 올릴 수 있다. 

 

Resources;
    ListBucketsS3Lambda: 
        Type: "AWS::Lambda::Function"
        Properties: 
          Handler: "index.handler"
          Role: 
            Fn::GetAtt: 
              - "LambdaExecutionRole"
              - "Arn"
          Runtime: "python3.7"
          Code: 
            S3Bucket: !Ref S3BucketParam
            S3Key: !Ref S3KeyParam