[AWS Lambda] Python Package 설치

2022. 10. 27. 20:49프로젝트 로그/테스트x솔루션 JIG 개발기

반응형

문제

 

자사의 웹 서비스가 잘 동작하는지 모니터링 후, 서비스가 동작 하지 않을 때 SLACK으로 메시지를 보내는 앱을 구현 하려고 한다. 

 

해당 앱은 AWS Lambda를 사용하여 동작 하려고 하는데, AWS Lambda에서 Python 코드를 동작할 때 requests 모듈이 없다는 에러가 발생 하였다.

 

해결 방법

Python Package를 Local PC에 다운로드 및 압축 파일 생성

1. Python 모듈 패키지를 다운로드 할 폴더 생성

아래와 같이 python-python 폴더 구조가 아닌 경우, AWS Lambda에서 패키지를 인식 하지 못하는 경우가 있으므로 해당 폴더 구조를 꼭 유지 해야 한다.

D:.
\---python
    \---python
    
$ cd python/python

2. requests 모듈과 slack 모듈 설치

D:\temp\python\python>pip install requests -t ./
D:\temp\python\python>pip install slack -t ./

3. 최 상위 python 폴더를 zip으로 압축

 

AWS Lambda Layer 생성

AWS Lambda Layer를 생성 하고, 해당 Layer에 앞에서 다운로드 한 Python Package의 압축 파일을 업로드 한다.

 

 

함수 생성

AWS Lambda를 이용하여 동작할 내용이 담겨 있는 함수를 생성 한다.

 

함수에 Layer 추가

 

함수 구현

import json
import requests
import slack
import datetime

SLACK_TOKEN = "xxxxxx"
SLACK_CHANNEL = "xxxxxx"

def send_slack_message(message):
    str_buf = datetime.datetime.now().strftime("[%m/%d %H:%M:%S] ") + message
    response = requests.post("https://slack.com/api/chat.postMessage", headers={"Authorization": "Bearer " + SLACK_TOKEN}, data={"channel": SLACK_CHANNEL, "text": message})


def lambda_handler(event, context):
    isError = False
    
    url = "http://test_site.com/api/v1/login"

    json_object = {
        "username" : "test",
        "password" : "test_password",
    }
    
    body = json.dumps(json_object)
    
    headers = {
        "Accept" : "application/json",
        "Authorization" : "Bearer {0}".format(""),
        "Content-Type" : "application/json"
    }
    
    try:
        response = requests.post(url, headers=headers, data=body, timeout=(0.1, 10)) # timeout=(conn_timeout, read_timeout)

        if response.status_code != 200:
            isError = True
            msg = "Server is not working. Response Status Code : {0}".format(response.status_code)
            send_slack_message(msg)

    except requests.exceptions.Timeout as errd:
        isError = True
        msg = "Server is not working. Timeout"
        send_slack_message(msg)

    except requests.exceptions.ConnectionError as errc:
        isError = True
        msg = "Server is not working. Connection Error"
        send_slack_message(msg)
        
    except requests.exceptions.HTTPError as errb:
        isError = True
        msg = "Server is not working. HTTPError"
        send_slack_message(msg)

    except requests.exceptions.RequestException as erra:
        isError = True
        msg = "Server is not working. Request Exception"
        send_slack_message(msg)
    
    if isError == True:
        return {
            'statusCode': 200,
            'body' : json.dump('Server is not working')
        }

    return {
        'statusCode': 200,
        'body': json.dumps('Server is alive')
    }

 

참고 자료

https://8iggy.tistory.com/67

 

Serverless | AWS Lambda Layer 외부 모듈 import하기

Lambda에서 함수를 배포하다 보면 python 기본 내장 모듈이 아닌 외부 모듈 사용이 필요한 상황이 있다. 그러나 third party 모듈 설치 없이 실행하면 오류가 발생한다. AWS Lambda는 Layer(계층)을 활용하여

8iggy.tistory.com

 

반응형