본문 바로가기
Dev/AWS

파이썬으로 SAM 사용하기 - 모듈 불러오기 에러/ 레이어 배포 - 패키지 에러

by 싯벨트 2025. 2. 19.
728x90

SAM 로컬테스트 모듈 불러오기 에러

핸들러가 위치한 파일이 다른 디렉토리에 있는 모듈을 읽어오지 못하는 에러가 발생했다.

ImportModuleError: No module named 'sample_module'

 

파일 구조는 다음과 같다.

root/
│── handlers/
│   ├── get_sample.py
│── src/
│   ├── sample.py

../src 경로에 있는 모듈을 임포트할 수 있도록 파이썬의 모듈 검색 경로(sys.path)에 추가했다.

 

import sys
import os

sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), "../src")))

SAM 템플릿에서는 함수 리소스에 codeUri 를 ./로 설정하고 핸들러 경로를 지정해줬다. 어차피 중복될 것이기에 Global 로 빼서 구현하면 더 좋다.

# 함수 리소스
Resources:
  GetSampleFunction:
    Type: AWS::Serverless::Function
    Properties:
      FunctionName: get-sample
      CodeUri: ./
      Handler: handlers/get_sample.handler

# 글로벌
Globals:
  Function:
    CodeUri: ./

레이어로 의존성 배포하기

sqlalchemy 패키지가 없다는 에러가 떴다. Lambda 환경에서 node_modules를 자동으로 인식하여 해당 폴더 내 패키지를 포함한 상태로 sam build가 진행되는 typescript와 다르게, python에서는 sam build가 Python의 requirements.txt를 자동으로 패키징하지 않기 때문에 수동으로 pip install -t를 수행해야 한다. 배포 효율성을 위해 레이어로 해결했다.

루트 폴더에 requirements.txt 작성하여 필요한 패키지를 입력했다. sqlalchemy만으로 레이어를 생성하니 에러가 나서 결과적으로 sqlalchemy, pymysql, cryptography을 입력했다. pymysql은 MySQL 데이터베이스와 연결하는 데 사용되고, cryptography는 mysql에서 caching_sha2_password 인증 방식을 사용할 경우 필요한 라이브러리다.

No module named 'sqlalchemy'
# requirements.txt
sqlalchemy
pymysql
cryptography

layer 생성

layer 에 python 디렉토리를 만들고, 의존성을 설치했다. 의존성을 설치한 디렉토리인 layer로 이동하여 python 디렉토리를 대상으로 압축을 한다.

mkdir -p layer/python
pip install -r requirements.txt -t layer/python/
cd layer
zip -r layer.zip python

layer 등록

.aws > credentials 에 등록한 프로필 이름과 리전까지 설정하여 레이어를 설정해준다.

aws lambda publish-layer-version \\
  --layer-name SampleLayer \\
  --zip-file fileb://layer.zip \\
  --compatible-runtimes python3.13 \\
  --profile sample_profile \\
  --region ap-northeast-2

sam 템플릿에서는 파리미터에 레이어를 설정해주고, 함수 리소스에 레이어를 설정해준다.

Parameters:
  SampleLayer:
    Type: String
    Default: SampleLayerARN

# 함수 리소스
Resources:
  GetSampleFunction:
    Type: AWS::Serverless::Function
    Properties:
      FunctionName: get-sample
      CodeUri: ./
      Handler: handlers/get_sample.handler
      Runtime: python3.13
      Layers:
        - !Ref SampleLayer  # 추가

로컬 테스트 에러

sam local start-api -p 4000 명령어 실행 시 아래 에러가 발생했다. 리전을 설정하라는 에러인데 SAM CLI 명령어(sam build, sam deploy 등)을 실행할 때 기본값을 저장하는 samconfig.toml 파일을 통해 디폴트 리전을 설정했다.

Lambda functions containers initialization failed because of You must specify a region.  
version = 0.1

[default.global.parameters]
region = "ap-northeast-2"