Serverless frameworkを使ってAWS Lambdaの関数をデプロイするチュートリアル.
プラグインを使って,Pythonの依存ライブラリが使える環境を作る.
以下をインストール/セットアップしておく.
- Serverless framework
- Docker
- AWSの認証情報
ServerlessでAWS Lambdaのサービスを作成する.
ここでは,sls-python-tutorialというサービス名にします.
sls create --template aws-python3 --path sls-python-tutorialsls-python-tutorialディレクトリに以下のファイルなどが生成される.
serverless.yml: Serverlessの構成ファイルhandler.py: 処理の関数
NumpyやPillowのライブラリを使えるようにするため,serverless-python-requirementsというプラグインを使います.
# ディレクトリへ移動
cd sls-python-tutorial
# プラグインを追加
sls plugin install -n serverless-python-requirementsserverless.ymlにserverless-python-requirements用の設定を追加する.
custom:
# serverless-python-requirementsの設定
pythonRequirements:
# 依存のコンパイルにdockerを使う
dockerizePip: true
# キャッシュの設定
useDownloadCache: true
useStaticCache: truedockerizePipはPure-pythonではないライブラリをLinux以外のホスト(windowsやmac)からデプロイする場合は必須です.
Pythonの依存をrequirements.txtを書く.
numpy
Pillowここでは,ライブラリを使った処理の例として,ライブラリのバージョンを取得してレスポンスに追加する.
import json
# インストールした依存をインポート
import numpy as np
import PIL.Image
import PIL
def hello(event, context):
# ライブラリのバージョンを取得
dependencies = {
"numpy": np.__version__,
"Pillow": PIL.__version__
}
body = {
"message": "Go Serverless v1.0! Your function executed successfully!",
"input": event,
"dependencies": dependencies
}
response = {
"statusCode": 200,
"body": json.dumps(body)
}
return response以下のコマンドでLambda関数をデプロイする.
# デプロイ
sls deploy --aws-profile <profile_name>
# 削除
sls remove --aws-profile <profile_name>以下のコマンドでデプロイされたLambda関数を実行する.
sls invoke -f hello
以下のように出力されれば成功
{
"statusCode": 200,
"body": "{\"message\": \"Go Serverless v1.0! Your function executed successfully!\", \"input\": {}, \"dependencies\": {\"numpy\": \"1.22.3\", \"Pillow\": \"9.0.1\"}}"
}