[AWS] Lambda 함수 로컬에서 테스트하기

sang yun Lee·2023년 5월 12일
0

Devops 실습

목록 보기
5/20

개요


이전에는 람다 함수를 SAM 을 통해 빌드하고 AWS Cloud 상에 배포한 뒤에 람다 함수를 테스트했었다. 그러나 배포를 하기 전에 미리 로컬 환경에서 테스트가 가능한 방법이 있어서 공유한다.

목표

hellow-world 람다 함수를 만들고 해당 함수를 로컬에서 호출해보기

최종 결과 프로젝트 깃허브 링크
https://github.com/SangYunLeee/lambda-test/tree/main/printEvent

테스트 방법


초기 조건:

  1. 람다 함수를 생성하는 프로젝트를 생성한다.

    $ 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 - Hello World Example With Powertools
            8 - Infrastructure event management
            9 - Serverless Connector Hello World Example
            10 - Multi-step workflow with Connectors
            11 - Lambda Response Streaming
            12 - Lambda EFS example
            13 - DynamoDB Example
            14 - Machine Learning
    Template: 5
    
    Which runtime would you like to use?
            1 - dotnet6
            2 - dotnetcore3.1
            3 - nodejs18.x
            4 - nodejs16.x
            5 - nodejs14.x
            6 - nodejs12.x
    Runtime: 5
    
    Based on your selections, the only Package type available is Zip.
    We will proceed to selecting the Package type as Zip.
    
    Based on your selections, the only dependency manager available is npm.
    We will proceed copying the template using npm.
    
    Would you like to enable X-Ray tracing on the function(s) in your application?  [y/N]: 
    
    Would you like to enable monitoring using CloudWatch Application Insights?
    For more info, please view https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/cloudwatch-application-insights.html [y/N]: 
    
    Project name [sam-app]: 
    
        -----------------------
        Generating application:
        -----------------------
        Name: sam-app
        Runtime: nodejs14.x
        Architectures: x86_64
        Dependency Manager: npm
        Application Template: quick-start-from-scratch
        Output Directory: .
        Configuration file: sam-app/samconfig.toml
    
        Next steps can be found in the README file at sam-app/README.md
  2. 함수를 수정하여 event 값을 볼 수 있도록 변경

  • exports.helloFromLambdaHandler = async (event) => {
        console.log(`event : ${event}`);
        return event;
    }
  1. 빌드한다.
  • 빌드
    $ cd sam-app
    $ sam build
  • 빌드 성공 결과
  1. 로컬에서 함수 실행
    • $ sam local invoke 시 함수 호출 됨을 확인 로그(Hellow from Lambda)
    • event.json 파일 추가
      # event.json
      {
          "TemperatureK": 281,
          "WindKmh": -3,
          "HumidityPct": 0.55,
          "PressureHPa": 1020
      }
    • event.json 을 인자로 사용해 호출
      • sam local invoke -e events/event.json
      • 로그가 찍히는 것을 확인
    • sam local start-api 을 통해 로컬에서도 api-gateway 테스트 또한 가능한다.

번외로,
aws 에 올린 람다함수를 로컬에서 호출할 수도 있다.

$ aws lambda invoke --function-name {Lambda함수의Arn를입력} --invocation-type Event  --payload '{ "Metadata": "Hello" }'  response.json --cli-binary-format raw-in-base64-out

참고자료
1. SAM을 이용하여 Lambda 로컬 개발 환경 구축하기
2. AWS: Invoking Lambda functions locally

0개의 댓글