본문 바로가기
AWS

AWS Chalice (챌리스)

by 내꿈은한량 2023. 6. 23.

https://github.com/aws/chalice

1. 개요

Chalice는 Python으로 서버리스 앱을 작성하기 위한 프레임워크입니다.

이 Python용 프레임워크를 사용하면 AWS Lambda를 사용하는 애플리케이션을 빠르게 생성하고 배포할 수 있습니다.

<< 제공 기능 >>

  • 앱을 생성, 배포 및 관리하기 위한 Command line tool.
  • Amazon API Gateway, Amazon S3, Amazon SNS, Amazon SQS 및 기타 AWS 서비스와의 통합을 위한 데코레이터 기반 API.
  • IAM Policy 생성.

AWS SAM(Serverless Application Model) 과 기능이 비슷하지만, AWS SAM과는 다르게 App 정의를 YAML 문법의 Template file이 아닌, Lambda 함수용 Python 코드만 이용하여, IAM, API Gateway, Lambda 함수를 모두 만들어 줍니다.

예를 들어, 다음과 같은 코드가 있다면

from chalice import Chalice

app = Chalice(app_name="helloworld")

@app.route("/")
def index():
    return {"hello": "world"}

 

아래의 명령어로

$ chalice deploy

아래의 AWS 서비스들이 생성됩니다.

  • Lambda 함수 실행을 위한 IAM Role
  • Lambda 함수
  • Lambda 함수 실행을 위한 API Gateway

이처럼, AWS 의 다양한 서비스들중에서 서버리스와 관련된 기능을 생성하기 위한 목적때문에 모든 AWS 서비스를 생성할 수는 없으며, 사용가능한 서비스도 제한적으로만 사용가능합니다.

하지만, 간단한 형태의 Serverless application 제작 목적이라면, Chalice 많은 도움을 줄 수 있습니다.

2. 사용 예

2-1. Rest API

from chalice import Chalice

app = Chalice(app_name="helloworld")

@app.route("/")
def index():
    return {"hello": "world"}

2-2. 주기적으로 실행되는 작업

매 5분마다 Lambda 함수 실행

from chalice import Chalice, Rate

app = Chalice(app_name="helloworld")

# Automatically runs every 5 minutes
@app.schedule(Rate(5, unit=Rate.MINUTES))
def periodic_task(event):
    return {"hello": "world"}

2-3. S3 Upload 이벤트를 처리

mybucket 라는 S3 버킷에 파일이 업로드될때마다 Lamdba 함수 실행

from chalice import Chalice

app = Chalice(app_name="helloworld")

# Whenever an object is uploaded to 'mybucket'
# this lambda function will be invoked.

@app.on_s3_event(bucket='mybucket')
def handler(event):
    print("Object uploaded for bucket: %s, key: %s"
          % (event.bucket, event.key))

2-4. SQS Queue 연동

my-queue-name 라는 SQS 큐에 메세지가 전송될때마다 Lamdba 함수 실행

from chalice import Chalice

app = Chalice(app_name="helloworld")

# Invoke this lambda function whenever a message
# is sent to the ``my-queue-name`` SQS queue.

@app.on_sqs_message(queue='my-queue-name')
def handler(event):
    for record in event:
        print("Message body: %s" % record.body)

3. 시작하기

3-1. 필수 환경

  • Python
    • 3.6 3.7, 3.8, 3.9 버전 지원

3-2. 설치

$ python3 -m pip install chalice

설치가 완료되면 아래 명령어로 설치 확인

$ chalice --help
Usage: chalice [OPTIONS] COMMAND [ARGS]...
...

3-3. 프로젝트 생성

chalice 명령어를 이용하여 새로운 프로젝트를 생성합니다.

$ chalice new-project helloworld

실행이 완료되면 helloworld 디렉토리가 생성됩니다. 결과는 다음과 같습니다.

$ cd helloworld
$ ls -la
drwxr-xr-x   .chalice
-rw-r--r--   app.py
-rw-r--r--   requirements.txt

생성된 파일중에서 app.py 파일을 열어보면 다음과 같습니다.

from chalice import Chalice

app = Chalice(app_name='helloworld')


@app.route('/')
def index():
    return {'hello': 'world'}

3-4. 배포

생성된 chalice 프로젝트는 chalice deploy 라는 명령어로 직접 배포할 수 있습니다.

3-5. 배포 결과 확인

배포가 완료되면 배포된 API Gateway의 Endpoint를 확인할 수 있습니다.

$ chalice deploy
Creating deployment package.
Creating IAM role: helloworld-dev
Creating lambda function: helloworld-dev
Creating Rest API
Resources deployed:
  - Lambda ARN: arn:aws:lambda:us-west-2:12345:function:helloworld-dev
  - Rest API URL: https://abcd.execute-api.us-west-2.amazonaws.com/api/

이 Endpoint URL을 이용하여 curl 명령어로 정상 동작 확인이 가능합니다.

$ curl https://qxea58oupc.execute-api.us-west-2.amazonaws.com/api/
{"hello": "world"}

3-6. 배포된 자원 삭제

필요시 chalice를 통해 배포된 자원들을 chalice delete 명령어로 삭제할 수 있습니다.

$ chalice delete
Deleting Rest API: abcd4kwyl4
Deleting function aws:arn:lambda:region:123456789:helloworld-dev
Deleting IAM Role helloworld-dev