두 달만에 접속해서 글을 남긴다. 그 사이에 이런저런 이벤트들이 많이 있어서 한동안 소홀히(?) 하다가, 초심으로 돌아가기 위해 정신차려 이렇게 글을 작성해 본다.(사실은 포스팅할 소재를 찾았다는 표현이 맞을듯 ㅠㅠ)
SaaS 기반의 AWS 아키텍처를 운영하다보니 기존 Lambda 관리 뿐만 아니라, 신규 Lambda를 작성해야 하는 경우가 발생하였다. 문제는 전 사수였던 분이 기존 Lambda 관리방법만 설명해 주었을 뿐, 신규 Lambda 작성 방법에 대한 코멘트나 인수인계가 전혀 없어서 시간을 들여서 신규 Lambda를 생성하고 배포하는 방법에 대해서 업무 진행을 하였다.
(초보자(?)이다 보니 분석하고 구성하는데 약 3주 정도 소요된듯하다.)
단순하게 AWS 자습서의 내용이면 어느정도 해결되겠지 생각하고 호기롭게 시작하였으나, 기존 AWS 아키텍처에서 발생하는 Trouble Shooting에 가로 막혀 원인 분석 및 해결하는데 많은 시간을 소모하였으니, 다른 업무때문에 더 까먹기 전에 내가 진행했던 방법을 기록해본다.
본 내용은 내가 진행했던 아키텍처 추가 부분 중 AWS SAM을 이용한 Lambda 생성 및 배포 방법이고, 신규 Lambda에 대한 CI/CD 구성 방법은 다음 포스팅으로 작성하려고 한다.
(관련 내용은 AWS 자습서를 참고하여 작성하였다.)
$ sam init
You can preselect a particular runtime or package type when using the `sam init` experience.
Call `sam init --help` to learn more.
Which template source would you like to use?
1 - AWS Quick Start Templates
2 - Custom Template Location
Choice: 1
Choose an AWS Quick Start application template
1 - Hello World Example
2 - Multi-step workflow
3 - Serverless API
4 - Scheduled task
5 - Standalone function
6 - Data processing
7 - Infrastructure event management
8 - Lambda EFS example
9 - Machine Learning
Template: 1
Use the most popular runtime and package type? (Python and zip) [y/N]: y
Project name [sam-app]: test-sam-01
Cloning from https://github.com/aws/aws-sam-cli-app-templates (process may take a moment)
-----------------------
Generating application:
-----------------------
Name: test-sam-01
Runtime: python3.9
Architectures: x86_64
Dependency Manager: pip
Application Template: hello-world
Output Directory: .
Next steps can be found in the README file at ./test-sam-01/README.md
Commands you can use next
=========================
[*] Create pipeline: cd test-sam-01 && sam pipeline init --bootstrap
[*] Test Function in the Cloud: sam sync --stack-name {stack-name} --watch
$ sam build
Running PythonPipBuilder:ResolveDependencies
Running PythonPipBuilder:CopySource
Build Succeeded
Built Artifacts : .aws-sam\build
Built Template : .aws-sam\build\template.yaml
Commands you can use next
=========================
[*] Invoke Function: sam local invoke
[*] Test Function in the Cloud: sam sync --stack-name {stack-name} --watch
[*] Deploy: sam deploy --guided
중요!
SAM deploy 시 CloudFormation을 통해 Lambda에 코드를 배포하는 구성이기 때문에 CloudFormation의 Stack name 정의가 중요하고, CloudFormation에서 Lambda로 배포하기 위한 IAM권한이 필수적이어야 한다. 마지막으로 Capabilities를 정의해야 하는데, Capabilities 정의 시 CAPABILITY_AUTO_EXPAND, CAPABILITY_NAMED_IAM, CAPABILITY_IAM 중 하나로 정의 해야한다. 나의 경우에는 CAPABILITY_IAM으로 설정하여 배포한다. Capabilities에 대한 세부 설명을 보고 싶으면 AWS 문서를 참고하기 바란다.
$ sam deploy
Configuring SAM deploy
======================
Looking for config file [samconfig.toml] : Found
Reading default arguments : Success
Setting default arguments for 'sam deploy'
=========================================
Stack Name [sam-app]: sam-app
AWS Region [ap-northeast-2]: ap-northeast-2
#Shows you resources changes to be deployed and require a 'Y' to initiate deploy
Confirm changes before deploy [Y/n]: y
#SAM needs permission to be able to create roles to connect to the resources in your template
Allow SAM CLI IAM role creation [Y/n]: n
Capabilities [['arn:aws:iam::711159021539:role/service-lambda-base-role']]: CAPABILITY_IAM
#Preserves the state of previously provisioned resources when an operation fails
Disable rollback [y/N]: y
Save arguments to configuration file [Y/n]: n
Looking for resources needed for deployment:
Managed S3 bucket: aws-sam-cli-managed-default-samclisourcebucket-1dqithuzhwtkj
A different default S3 bucket can be set in samconfig.toml
File with same data already exists at sam-app/4f55b8dfdd4844877602ffbf3b2c4138, skipping upload
Deploying with following values
===============================
Stack name : sam-app
Region : ap-northeast-2
Confirm changeset : True
Disable rollback : True
Deployment s3 bucket : aws-sam-cli-managed-default-samclisourcebucket-1dqithuzhwtkj
Capabilities : ["CAPABILITY_IAM"]
Parameter overrides : {}
Signing Profiles : {}
Initiating deployment
=====================
Waiting for changeset to be created..
CloudFormation stack changeset
---------------------------------------------------------------------------------------------------------------------
Operation LogicalResourceId ResourceType Replacement
---------------------------------------------------------------------------------------------------------------------
+ Add SamAppAliasdev AWS::Lambda::Alias N/A
+ Add SamAppVersioncec8294a1c AWS::Lambda::Version N/A
+ Add SamApp AWS::Lambda::Function N/A
---------------------------------------------------------------------------------------------------------------------
Changeset created successfully. arn:aws:cloudformation:ap-northeast-2:711159021539:changeSet/samcli-deploy1662534079/34e752cd-667c-47a1-a503-36b1cdac3d9f
Previewing CloudFormation changeset before deployment
======================================================
Deploy this changeset? [y/N]: y
2022-09-07 16:01:29 - Waiting for stack create/update to complete
CloudFormation events from stack operations
---------------------------------------------------------------------------------------------------------------------
ResourceStatus ResourceType LogicalResourceId ResourceStatusReason
---------------------------------------------------------------------------------------------------------------------
CREATE_IN_PROGRESS AWS::Lambda::Function SamApp -
CREATE_IN_PROGRESS AWS::Lambda::Function SamApp Resource creation Initiated
CREATE_COMPLETE AWS::Lambda::Function SamApp -
CREATE_IN_PROGRESS AWS::Lambda::Version SamAppVersioncec8294a1c -
CREATE_COMPLETE AWS::Lambda::Version SamAppVersioncec8294a1c -
CREATE_IN_PROGRESS AWS::Lambda::Version SamAppVersioncec8294a1c Resource creation Initiated
CREATE_IN_PROGRESS AWS::Lambda::Alias SamAppAliasdev Resource creation Initiated
CREATE_IN_PROGRESS AWS::Lambda::Alias SamAppAliasdev -
CREATE_COMPLETE AWS::Lambda::Alias SamAppAliasdev -
CREATE_COMPLETE AWS::CloudFormation::Stack sam-app -
---------------------------------------------------------------------------------------------------------------------
Successfully created/updated stack - sam-app in ap-northeast-2