AWS SAM의 Lambda Functions with Node.js + API Gateway 최소 구성

6618 단어 CloudFormationAWS
AWS SAM을 사용하여 Lambda + API Gateway를 사용해 보았습니다. Lambda의 언어 환경은 Node.js입니다.

SAM CLI 도구 설치



Installing the AWS SAM CLI on Linux - AWS Serverless Application Model

이것을 읽으면 리눅스에 Homebrew를 넣으려고 하고 있습니다만, 거기까지는 하고 싶지 않으므로, pip 그리고 넣습니다. 내 환경은 이제 pipenv를 사용하기 때문에 명령은 다음과 같습니다.

빈 디렉토리에서,
$ pipenv install aws-sam-cli

$ pipenv run sam --version
SAM CLI, version 0.37.0

sam 명령으로 편지지 만들기


sam init 라는 명령을 실행하면 몇 가지 질문 받기 때문에 거기에 대답하면 편지지가되는 파일 세트를 생성합니다. 디렉토리를 하나 파고 줍니다.

다음은 예입니다. 프로젝트 이름은 적합합니다. sampipenv 로 설치했으므로 명령 앞에 pipenv run 를 붙입니다.
$ pipenv run sam init --runtime nodejs12.x
Which template source would you like to use?
        1 - AWS Quick Start Templates
        2 - Custom Template Location
Choice: 1

Project name [sam-app]: hellonodealambda

Allow SAM CLI to download AWS-provided quick start templates from Github [Y/n]: Y

-----------------------
Generating application:
-----------------------
Name: hellonodealambda
Runtime: nodejs12.x
Dependency Manager: npm
Application Template: hello-world
Output Directory: .

Next steps can be found in the README file at ./hellonodealambda/README.md

그러면 다음과 같은 파일 구성이 됩니다.
$ find . -type f
./hellonodealambda/events/event.json
./hellonodealambda/README.md
./hellonodealambda/packaged.yaml
./hellonodealambda/hello-world/app.js
./hellonodealambda/hello-world/package.json
./hellonodealambda/hello-world/.npmignore
./hellonodealambda/hello-world/tests/unit/test-handler.js
./hellonodealambda/.gitignore
./hellonodealambda/template.yaml
./Pipfile
./Pipfile.lock
Pipfile*sam 를 설치했을 때의 파일이며, pipenv 가 필요할 뿐입니다. Project name의 디렉토리( hellonodealambda )가 sam init 로 생성된 파일입니다. 이 이후는 hellonodealambda 디렉토리내에서 작업합니다.
$ cd hellonodealambda

AWS에 배포


sam package 를 실행하여 CloudFormation 템플릿 파일을 만듭니다. aws cloudformation package 에 상당하는 것이라고 생각합니다. 이렇게하면 Lambda에 배포하는 소스 세트가 임시 S3에 업로드되고 업로드 대상을 참조하는 packaged.yaml가 작성됩니다.

참고
AWS CloudFormation을 조금 이해했습니다. - Qiita

명령은 이런 느낌.
$ pipenv run sam package --profile AWS_CREDENTIAL_PROFILE_NAME --template-file template.yaml --output-template-file packaged.yaml --s3-bucket MYBUCKET_NAME --s3-prefix hellonodealambda

그런 다음 sam deploy를 실행하여 CloudFormation에 배포하고 관련 AWS 리소스를 생성합니다. aws cloudformation deploy 에 해당합니다.
$ pipenv run sam deploy --profile AWS_CREDENTIAL_PROFILE_NAME --region ap-northeast-1 --template-file packaged.yaml --stack-name hellonodealambda --capabilities CAPABILITY_IAM
--region 가 필요할 때와 그렇지 않은 때가 있다고 생각합니다만, 자세한 것은 잘 모릅니다. ~/.aws/config 에 region을 지정하고 싶습니다. sam deploy 때 이것이 없으면 내 계정에서 botocore.exceptions.NoRegionError: You must specify a region.라는 오류가 발생했습니다.
--capabilities CAPABILITY_IAM 의 의미도 모릅니다. 이것이 없으면
Error: Failed to create changeset for the stack: hellonodealambda, Parameter validation failed:
Invalid type for parameter Capabilities, value: None, type: <class 'NoneType'>, valid types: <class 'list'>, <class 'tuple'>

라는 오류가 되어 버렸습니다.

관리 콘솔의 API Gateway에서 Resources 페이지에서 Actions에 있는 Deploy API라고 하면 API에 액세스할 수 있습니다.


$ curl 'https://XXXX.execute-api.ap-northeast-1.amazonaws.com/Stage/hello'
{"message":"hello world"}

GET 매개변수 수신



API로 GET 매개변수를 Lambda가 수신할 수 있도록 합니다.
app.js 의 내용을 다음과 같이 해 봅니다. API로 전달한 GET 매개변수를 로그와 응답에 모두 포함합니다.
        console.log(event.queryStringParameters);
        console.log(event.multiValueQueryStringParameters);
        response = {
            'statusCode': 200,
            'body': JSON.stringify({
                message: 'hello world',
                params: event.queryStringParameters,
                multiParams: event.multiValueQueryStringParameters,
            })
        }

실행해 보겠습니다.
$ curl 'https://XXXX.execute-api.ap-northeast-1.amazonaws.com/Stage/hello?pa=A&pa=AA&pb=BB'
{"message":"hello world","params":{"pa":"AA","pb":"BB"},"multiParams":{"pa":["A","AA"],"pb":["BB"]}}

같은 이름의 파라미터를 복수 건네주면(자), event.queryStringParameters 에는 나머지의 것이 우선되어, event.multiValueQueryStringParameters 에는 배열 형식으로 전부가 포함되는 것 같습니다.

이상.

좋은 웹페이지 즐겨찾기