1
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

Lambdaに[/tmp]を利用してpythonライブラリをインストール

Last updated at Posted at 2020-03-26

#問題
Lambdaのデプロイパッケージのサイズ制限で、250 MB を超えることはできません。
#解決方法
Lambda Layerを作成
Lambdaの[/tmp]フォルダー(512M)を利用してライブラリをインストール
今回は2の方法を説明します。
#requirements.txtファイルを作成

requirements-lambda.txt
numpy==1.16.3
create.sh
#!/bin/bash

if [ -d "deploy" ]; then rm -Rf deploy; fi
mkdir deploy
pip install -r requirements-lambda.txt -t deploy/requirements-lambda/
cd deploy/requirements-lambda
rm -r PIL
rm -r Pillow*
zip -9 -r ../lambda-requirements.zip .
cd ..
rm -r requirements-lambda

#LambdaにhandleプログラムにUnzip(サイズは50MB未満)

handle.py
import os
import sys
import zipfile

pkgdir = '/tmp/requirements'
zip_requirements = 'lambda-requirements.zip'

if os.environ.get("AWS_EXECUTION_ENV") is not None:
    if not os.path.exists(pkgdir):

        root = os.environ.get('LAMBDA_TASK_ROOT', os.getcwd())
        zip_requirements = os.path.join(root, zip_requirements)
        zipfile.ZipFile(zip_requirements, 'r').extractall(pkgdir)

        sys.path.append(pkgdir)

#S3からダウンロードしてUnzip(サイズは50MB以上)

handle.py
import boto3
import os
import sys
import zipfile

REQUIREMENTS_BUCKET_NAME = ''
REQUIREMENTS_KEY = ''

pkgdir = '/tmp/requirements'
zip_requirements = '/tmp/lambda-requirements.zip'

sys.path.append(pkgdir)

if os.environ.get("AWS_EXECUTION_ENV") is not None:
    if not os.path.exists(pkgdir):

        s3 = boto3.resource('s3')
        bucket = s3.Bucket(REQUIREMENTS_BUCKET_NAME)
        bucket.download_file(REQUIREMENTS_KEY, zip_requirements)

        zipfile.ZipFile(zip_requirements, 'r').extractall(pkgdir)
        os.remove('zip_requirements')

        sys.path.append(pkgdir)

1
2
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
1
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?