LoginSignup
13
7

More than 3 years have passed since last update.

Lambda Layer と X-Ray

Last updated at Posted at 2018-12-05

はじめに

AWS re:Invent 2018 でLambdaのLayer機能が発表されたのでどういう使い方をするかなーと考えてみました。
使い方についてはもういろんなサイトで公開されているので割愛。

今回は、分析時に便利なX-Rayの導入を簡素化させるためのLayerを用意してみました。

Lambdaのコードや設定はここを参考にしています。

tl;dr

  • Layerはパッケージを作るときに言語毎のルールがあるのでそれに従わないといけない
  • Layerは/optに展開される
  • あとは通常のライブラリの使い方と同じかんじ
  • X-Rayやrequestsのライブラリを個別に入れる手間が少しだけはぶける。(既存のLambdaに手を加える必要はある。)

やったこと

前提

  • ALB、Lambdaは東京リージョンに作成
  • Layerの言語はPython 3.6
  • Layerを追加したいLambdaはすでに作成ずみ(Python 3.6)

Layerのパッケージの作成

今回はX-Rayとrequestsを含めたLayerを作成する

$ mkdir python
$ touch python/layer.py
$ pip install requests -t python/
$ pip install aws-xray-sdk -t python/

layer.pyを編集する

layer.py
from aws_xray_sdk.core import xray_recorder
from aws_xray_sdk.core import patch_all

patch_all()

zipにしたらパッケージの準備完了

$ zip -r python.zip python/

Layerの作成

$ aws lambda publish-layer-version --layer-name x-ray-layer --description "x-ray layer" --license-info "MIT" --content S3Bucket=xxxx,S3Key=python.zip --compatible-runtimes python3.6

LambdaにLayerを追加

$ aws lambda update-function-configuration --function-name <function_name> --layers arn:aws:lambda:ap-northeast-1:<account_id>:layer:x-ray-layer:1

LambdaのX-Rayを有効化

$ aws lambda update-function-configuration --function-name <function_name> --tracing-config '{"Mode": "Active"}'

これで、準備は完了。
あとはLayerを追加したLambdaに以下の一文を追加するとX-Rayでトレースが見られるようになる。

import layer

Layerを適用したLambdaのデプロイ用のパッケージは容量減るのですっきりした感じがする。
(実行時のモジュールサイズはへらない。)

13
7
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
13
7