[TIL] AWS Lambda .NET Core : December 9, 2021

RE_BROTHER·2021년 12월 9일
0

TIL

목록 보기
38/41
post-thumbnail

AWS Lambda Docker(.NET)

AWS Lambda에 .NET Core 프로젝트를 배포하는 과정을 적어볼 예정이다.

AWS Toolkit for Visual Studio

AWS 공식 문서를 참고하여 진행한다. AWS에서는 Visual Studio 2017/2019에 대한 공식 문서만 제공하고 있다.
Visual Studio 2022(이하 VS2022)는 아직 공식 문서가 작성되진 않았지만, VS2022를 지원하는 AWS Toolkit Preview는 제공되고 있으니 일단 설치해보기로 한다.

> AWS Toolkit for Visual Studio Download


AWS Toolkit download & install


위에서 언급한 내용대로 VS2022로 설치한다.

[install] 버튼 1회만 클릭하면 그리 오래걸리지 않는 시간내에 설치가 완료된다. 솔직히 카톡 PC버전 설치보다 쉬운듯.


Basic AWS Lambda Project

설치가 완료된 상태에서 VS2022를 실행하게 되면 AWS 관련 템플릿들이 추가된 것을 볼 수 있다.

징그럽게 많다..


AWS Lambda Project (.NET Core - C#)를 선택하고 프로젝트의 이름과 위치를 지정한다.


만들기를 클릭하면 위와 같이 Blueprint를 선택하는 창이 뜨는데 당황하지말고 Empty Function을 선택하면 된다.


AWS IAM 콘솔에서 발급받은 Access Key와 Secret Key를 입력하고 Save 하면 된다. 혹시나 Secret Key를 분실한 경우 새로 발급받아야함.

[참고] AWS 자격 증명 프로필 생성 문서

정상적으로 연결되었다면 좌측에 AWS Explorer에 서비스들이 출력된다. 혹시나 여기서도 AWS Explorer가 생성되지 않았다면 [보기] -> [AWS Explorer] 또는 Ctrl + K, A 숏컷을 사용하면 된다.

솔루션 탐색기에 aws-lambda-tools-defaults.json, Function.cs 파일이 있는데 해당 파일 설명은 AWS 공식 문서를 보는게 좋을 것 같다.

aws-lambda-tools-defaults.json

프로젝트의 일부로 생성된 파일을 보여줍니다. Lambda 도구가 기본적으로 읽는 이 파일의 필드를 사용하여 빌드 옵션을 설정할 수 있습니다. Visual Studio의 프로젝트 템플릿에는 기본값이 있는 이러한 필드가 많이 포함되어 있습니다. function-handler 필드는 Lambda 함수가 실행될 때 실행되는 메서드를 지정합니다. 함수 핸들러를 지정하는 경우 필드는 게시 마법사에 미리 채워져 있습니다. 함수, 클래스 또는 어셈블리의 이름을 바꾸면 aws-lambda-tools-defaults.json 파일의 필드도 업데이트해야 합니다.
{
  "Information": [
    "This file provides default values for the deployment wizard inside Visual Studio and the AWS Lambda commands added to the .NET Core CLI.",
    "To learn more about the Lambda commands with the .NET Core CLI execute the following command at the command line in the project root directory.",
    "dotnet lambda help",
    "All the command line options for the Lambda command can be specified in this file."
  ],
  "profile": "",
  "region": "",
  "configuration": "Release",
  "framework": "netcoreapp3.1",
  "function-runtime": "dotnetcore3.1",
  "function-memory-size": 256,
  "function-timeout": 30,
  "function-handler": "AWSLambda_basic::AWSLambda_basic.Function::FunctionHandler"
}

Function.cs

Lambda 함수로 노출할 C# 함수를 정의합니다. 이것은 FunctionHandlerLambda 함수가 실행될 때 실행되는 Lambda 기능입니다. 이 프로젝트에는 입력 텍스트 FunctionHandler를 호출하는 하나의 함수가 정의되어 ToUpper()있습니다.
// Function.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

using Amazon.Lambda.Core;

// Assembly attribute to enable the Lambda function's JSON input to be converted into a .NET class.
[assembly: LambdaSerializer(typeof(Amazon.Lambda.Serialization.SystemTextJson.DefaultLambdaJsonSerializer))]

namespace AWSLambda_basic
{
    public class Function
    {
        
        /// <summary>
        /// A simple function that takes a string and does a ToUpper
        /// </summary>
        /// <param name="input"></param>
        /// <param name="context"></param>
        /// <returns></returns>
        public string FunctionHandler(string input, ILambdaContext context)
        {
            return input?.ToUpper();
        }
    }
}

Test

가장 기본적인 테스트만 진행할 계획이였기 때문에 Function.cs에 기본적으로 작성되어있는 ToUpper() 기능으로 테스트를 진행할 예정이다.

AWS Explorer에서 AWS Lambda 우클릭 후 Publish to AWS Lambda 선택

실제로 프로젝트 진행시에는 .NET Core v3.1을 사용할 계획은 없지만 이번에는 반항하지 않고 AWS 공식 문서에서 시키는데로 따라해본다.
VS2019, VS2017과는 아주 조금 다른 창이 뜨는데 엄청 많이 다른건 아니니까 요령껏 작성했다.

다음 페이지에선 크게 만질만한 옵션이 없다 Role NameAWSLambdaBasicExecutionRole로 변경해주고 업로드한다.

업로드가 정상적으로 완료되면 업로드 윈도우가 자동으로 종료되고, AWS Explorer를 보면 AWS Lambda에 방금 추가한 Function이 추가되어있다.

Error : Could not find the required '{Assembly}.deps.json'

{
  "errorType": "LambdaException",
  "errorMessage": "Could not find the required 'AWSLambda_basic.deps.json'.
                  This file should be present at the root of the deployment package."
}

새롭게 생성된 Function 윈도우에서 샘플 테스트를 진행하는데 보고 따라했음에도 에러가 생긴다.
참 신기한 세상이다.

내 머리가 레전드인건지..

해당 오류는 *.deps.json 파일이 없어서 생기는 오류인데, *.deps.json 파일은 프로젝트를 publish하게 되면 .\bin\Debug\\{runtime}\publish\ 디렉터리에 생성되는 파일이다.
AWS Lambda에 업로드하기 전에 Visual Studio에서 dotnet publish 후 파일 생성까지 확인.


해결

dotnet publish한 프로젝트를 다시 AWS Lambda에 업로드했지만 해당 오류는 해결되지 않았다.
이래저래 테스트를 하던 중 AWS Lambda 업로드 중 Rold Name을 기존 AWSLambdaBasicExecutionRole에서 AWSLambdaRole (Default policy for AWS Lambda Service Role.)으로 변경했고, AWS Lambda에 업로드된 ToUpper() 함수는 정상적으로 동작했다.


Ending

한동안 기록없이 코드만 치다보니 감이 떨어진듯하다. 습관이 이렇게 무섭다.

앞으로 기록할 것들

  • AWS Lambda에 업로드한 코드 수정하기(json parsing)
  • dotnet publish 패키지 증발 현상
  • AWS Lambda 함수와 AWS API Gateway 연동하기
  • AWS EC2 ubuntuDocker 환경 구축하기 + ASP.NET Core Docker Image

기록할 일이 많다는건 좋은 상황인지, 아닌지.

[참고] AWS Lambda에 C# Handler 만들기 - devstarsj

profile
I hope the All-Rounder Developer & Researcher

0개의 댓글