티스토리 뷰

 

현재 서비스는 대부분 Java/Kotlin으로 구현되어 있어

 

갑자기 진행된 Python 프로젝트를 어떻게 배포할까에 대한 고민이 있었다.

 

스케줄러로 하루에 한번돌기 때문에 부담은 없지만, 내부 패키지를 많이 사용하는 프로젝트다.

 

대략 3가지 방안이 논의됐다.

1. AWS Lambda에 배포
2. Spot EC2에 배포
3. 쿠버네티스 컨테이너에 배포

 

DB를 따로 사용하지 않기 때문에, 1번 방안부터 알아봤다.

 

결론부터 이야기하면, 해당 프로젝트에 이미지 프로세싱이 들어가있어서 AWS Lambda는 후보군에서 바로 제외됐다.

 

그래도 serverless 프레임워크를 써서 파이썬 Lambda를 생성해봤기 때문에 정리하고 넘어가려고한다.

 

python만의 특이한 옵션들이 있어서 프로젝트 생성/관리에 조금 어려움이 있었다. 

 

그래도 그냥 사용하면 재미가 없으니, 이번에도 역시 S3 연동을 하고 프로젝트와 동일하게 스케줄러로 구성했다.

 

의존성 패키지 관리를 위한 가상화

$ virtualenv automated_writing
$ source automated_writing/bin/active
$ pip install python-dotenv
$ pip install requests
$ pip install boto3
$ pip freeze > requirements.txt
$ deactivate

requirements.txt가 잘 생성되었다.

 

serverless.yml

service: automated-writing
frameworkVersion: '3'
useDotenv: true

plugins:
  - serverless-python-requirements

custom:
  pythonRequirements:
    dockerizePip: non-linux

provider:
  name: aws
  region: ap-northeast-2
  architecture: arm64
  runtime: python3.10
  deploymentBucket:
    name: ${env:DEPLOY_BUCKET_NAME}
  logRetentionInDays: 30
  environment:
    STAGE: ${sls:stage}
    S3_BUCKET: ${env:S3_BUCKET}
  iam:
    role:
      name: ps-automated-writing
      path: /lambda/
      statements:
        - Effect: Allow
          Resource: arn:aws:s3:::${env:S3_BUCKET}/*
          Action: s3:PutObject
  tags:
    Team: Metashare
    Service: polarishare
    Stage: ${sls:stage}
    GitHub: https://github.com/[github address]

package:
  exclude:
    - node_modules/**
    - automated_writing/**

functions:
  automated_writing:
    handler: python/automated_writing.run
    url: true
    events:
      - schedule: rate(1 hour)

node.js와 Go랑은 다르게 몇 가지 새로 추가한 옵션들이 있다.

 

1. plugin.serverless-python-requriements

Lambda에 배포할 때, 의존성 패키지들을 작성한 requirements.txt도 함께 배포한다. 이 의존성 패키지를 자동 패키징해주는 옵션이다. 로컬에서 작업하면 node_modules가 함께 생성되기 때문에 serverless로 배포할 떄 exclude 옵션으로 제외시켜 줬다.

 

2. custom.pythonRequirements

내 로컬 OS는 Windows 10이다. 하지만 Lambda의 OS는 Linux기 때문에 OS에 따라 패키지의 옵션이 달라지는 경우, 배포가 정상적으로 진행 되지않는다. 때문에 내 로컬 옵션에 맞춰 non-linux를 설정해주면 docker로 빌드해서 호환성 문제를 해결하고 배포된다.

이 옵션을 사용할 경우 docker가 반드시 설치되어 있어야한다.

 

3. events schedue 옵션

한시간마다 cloudwatch에서 event 트리거로 자동으로 동작시켜준다. 올바르게 설정되면 lambda 콘솔에 트리거가 나타난다. 

 

1시간마다 트리거가 동작하도록 했다.

 

4. userDotenv 설정

dotEnv 파이썬 패키지를 사용할 수 있다. 스테이지별 정보를 여기에 담아두고 가져다 쓰도록 했다.

 

간단한 코드

import json
import boto3
import datetime
import os

def run(event, context):  
    s3 = boto3.client('s3')

    current_time = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')

    bucket_name = os.getenv('S3_BUCKET')

    if not bucket_name:
        return {"statusCode": 500, "body": json.dumps({"message": "S3_BUCKET environment variable is not set"})}

    # File to upload
    file_name = '/tmp/current_time.txt'
    file_content = f'Current Time: {current_time}'
    
    # Write the current time to a file
    with open(file_name, 'w') as file:
        file.write(file_content)

    # Upload the file to S3
    try:
        response = s3.upload_file(file_name, bucket_name, file_name)
        os.remove(file_name)
    except Exception as e:
        return {"statusCode": 500, "body": json.dumps({"message": "Failed to upload file to S3", "error": str(e)})}

    # Success response
    body = {
        "message": "File uploaded successfully to S3",
        "input": event,
    }

    return {"statusCode": 200, "body": json.dumps(body)}

boto3라는 강력한 패키지를 이용해 다른 언어와 비교해서 S3 를 가장 쉽게 사용할 수 있다. 

 

별다른 건 없고 현재 시각을 저장하고 txt 파일을 만들어 S3에 저장한다.

 

스케줄러로 돌기 때문에 1시간마다의 현재시간을 저장할 것이다.

 

여기서 조금 중요한게 있는데 파일의 저장 경로다.

 

AWS Lambda에서 읽고 쓰기가 가능한 경로는 /tmp 밖에 없다는 점에 유의해야한다.

https://aws.amazon.com/ko/blogs/korea/choosing-between-aws-lambda-data-storage-options-in-web-apps/

 

총 512MB 밖에 제공하지 않으며 영구 저장소가 아니니 사용에 주의 할 것!!.

 

github

https://github.com/imsosleepy/serverless-lambda/tree/main/aws-python-project

 

마치며

일단 serverless framework에 대한 포스팅은 한동안 없지 싶다.

 

Node.js, GO, Python 세 언어로 Lambda를 관리하려니까 조금 피곤하다.

(주 언어인 Java로는 아직 사용해보지 않았다는게 함정)

 

이 파이썬 프로젝트가 들어갈 가장 유력한 곳이 쿠버네티스 컨테이너인데, 아직 ArgoCD의 사용법이 익숙하지 않다.

 

쿠버네티스는 언제쯤 익숙해질까?

공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2024/07   »
1 2 3 4 5 6
7 8 9 10 11 12 13
14 15 16 17 18 19 20
21 22 23 24 25 26 27
28 29 30 31
글 보관함