LoginSignup
9
4

More than 3 years have passed since last update.

Serverless FrameworkとAWS Lambda with Pythonの環境にpipインストール

Last updated at Posted at 2021-01-05

pipインストールが必要なAWS LambdaのPythonスクリプトをServerless Frameworkでデプロイする方法です。

gemインストールが必要なAWS LambdaのRubyスクリプトについては前回の記事で書きました。

手順概要

プラグインを入れれば簡単にできます。

  1. serverless plugin install -n serverless-python-requirements
  2. requirements.txt 作成
  3. あとは普通にデプロイすると勝手にいろいろやってくれる

手順詳細

Serverless Frameworkのサービス作成

$ serverless create --template aws-python3
Serverless: Generating boilerplate...
 _______                             __
|   _   .-----.----.--.--.-----.----|  .-----.-----.-----.
|   |___|  -__|   _|  |  |  -__|   _|  |  -__|__ --|__ --|
|____   |_____|__|  \___/|_____|__| |__|_____|_____|_____|
|   |   |             The Serverless Application Framework
|       |                           serverless.com, v2.16.1
 -------'

Serverless: Successfully generated boilerplate for template: "aws-python3"
Serverless: NOTE: Please update the "service" property in serverless.yml with your service name

ファイルが3つ生成されます。

.gitignore
handler.py
serverless.yml

プラグインインストール

serverless-python-requirements というプラグインをインストールします。

$ serverless plugin install -n serverless-python-requirements

以下のファイルやディレクトリが増えます。

node_modules
package.json
package-lock.json

Serverless FrameworkがNode.jsで実装されているので、Pythonのプロジェクトなのに node_modulespackage.json が存在することになるようです。

ソースコード

serverless.yml

serverless.yml は以下の内容にします。 plugins のところの記述はプラグインをインストールすると勝手に追記されています。

serverless.yml

service: sample

frameworkVersion: '2'

provider:
  name: aws
  runtime: python3.8
  region: ap-northeast-1

functions:
  hello:
    handler: handler.hello

plugins:
  - serverless-python-requirements

requirements.txt

サンプルのライブラリとして jpholiday というライブラリを使ってみます。日本の祝日を判定するライブラリです。

requirements.txt を作成し、以下の内容にします。ライブラリ名1行のみのファイルです。

jpholiday

サンプルとして jpholiday というライブラリを使ってみます。日本の祝日を判定するライブラリです。

Pythonソースコード

handler.py

import datetime
import jpholiday

def hello(event, context):
    holidayName = jpholiday.is_holiday_name(datetime.date(2021, 8, 8))
    print(holidayName) # CloudWatch に "山の日" と書き出される

デプロイ

ここまで作成してから serverless コマンドでデプロイすると、Lambda本体だけでなく、 serverless コマンドが自動でライブラリをインストールしたイメージを作成し、AWS LambdaのLayerとしてアップロードしてくれます。

$ serverless deploy -v

実行

デプロイ後にAWSマネジメントコンソールでLambdaを見ると次のように見えます。

image.png

Rubyと違ってLayerではなくLambdaに直接ライブラリが保管されるようです。

2021/01/29 追記
serverless.ymlに設定を書き加えればLayerになりました。次の記事に書きました。
AWS Lambda + Python + Serverless FrameworkのLayerにpipインストール

リンク

9
4
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
9
4