【aws】CloudFormationでLambda Layerを使ってライブラリが使えるLambdaをデプロイする【CloudFormation】

CloudFormationでlambdaをデプロイする

この記事の続きです

やること

ライブラリを配置するpath

今回はLambdaLayerにライブラリを追加し、メインの関数ではLayerを使うことでライブラリを使った関数を使えるようにします。

project
├─.gitignore
├─buildspec.yaml
├─package-lock.json
├─package.json
├─readme
├─template.yaml
│  
├─layers
Project
│  .gitignore
│  buildspec.yaml
│  package-lock.json
│  package.json
│  readme
│  template.yaml
│  
├─layers
│  └─nodejs
│      │  package-lock.json
│      │  package.json
│      │  
│      └─node_modules
├─node_modules
└─src
    └─functions
        └─test
                index.ts
         

AWSの指定通りにフォルダを作る

nodejsフォルダ配下にnode_modules及びpackage.json,package-lock.jsonを配置します。

Lambda関数でライブラリを利用する

import { v4 as uuidv4 } from "uuid";
export function handler(event: any, context: any, callback: any): void {
  const uuid = uuidv4() as string;
  console.log(`uuid:${uuid}`);
}

今回はUUIDを使ってランダムな数字を出力するlambdaをデプロイします。

npm install

プロジェクト直下

・npm init
・npm i uuid(ローカルで動作確認しないなら不要)
・npm i @types/uuid

{
  "name": "cicd-test-repository-2021",
  "version": "1.0.0",
  "lockfileVersion": 1,
  "requires": true,
  "dependencies": {
    "@types/uuid": {
      "version": "8.3.0",
      "resolved": "https://registry.npmjs.org/@types/uuid/-/uuid-8.3.0.tgz",
      "integrity": "sha512-eQ9qFW/fhfGJF8WKHGEHZEyVWfZxrT+6CLIJGBcZPfxUh/+BnEj+UCGYMlr9qZuX/2AltsvwrGqp0LhEW8D0zQ=="
    },
    "uuid": {
      "version": "8.3.2",
      "resolved": "https://registry.npmjs.org/uuid/-/uuid-8.3.2.tgz",
      "integrity": "sha512-+NYs2QeMWy+GWFOEm9xnn6HCDp0l7QBD7ml8zLUmJ+93Q5NF0NocErnwkTkXVFNiX3/fpC6afS8Dhb/gz7R7eg=="
    }
  }
}
{
  "name": "cicd-test-repository-2021",
  "version": "1.0.0",
  "description": "readme",
  "main": "index.js",
  "dependencies": {
    "@types/uuid": "^8.3.0",
    "uuid": "^8.3.2"
  },
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "repository": {
    "type": "git",
    "url": "https://git-codecommit.ap-northeast-1.amazonaws.com/v1/repos/cicd-test-repository-2021"
  },
  "author": "",
  "license": "ISC"
}

xxxx/nodejs直下

・npm init
・npm i uuid 

lambdaで利用するファイルはあくまでもindex.tsをコンパイルしたindex.jsなので型情報(@types)は必要ありません。

buildspec.yaml

version: 0.2

phases:
  install:
    commands:
      - npm install -g typescript
      - npm ci
  build:
    commands:
      - curl "https://awscli.amazonaws.com/awscli-exe-linux-x86_64.zip" -o "awscliv2.zip"
      - unzip awscliv2.zip
      - ls -l /root/.pyenv/shims/aws
      - ./aws/install --bin-dir /root/.pyenv/shims --install-dir /usr/local/aws-cli --update
      - cd layers/nodejs
      - npm ci
      - cd ${CODEBUILD_SRC_DIR}
      - tsc src/functions/test/index.ts
  post_build:
    commands:
      - aws --version
      - aws cloudformation package --template-file template.yaml --output-template-file packaged.yaml --s3-bucket cicd-test-bucket-2021
      - aws cloudformation deploy --template-file packaged.yaml --stack-name testFunction --capabilities CAPABILITY_IAM
      - cat packaged.yaml
artifacts:
  files:
    - packaged.yaml
  - cd layers/nodejs
  - npm ci
  - cd ${CODEBUILD_SRC_DIR}
  - tsc src/functions/test/index.ts

前の記事と変更点はこの4行で
nodejs配下に移動し、npm ci
プロジェクト配下に戻ってコンパイル
を行っています。
${CODEBUILD_SRC_DIR}はCodeBuildの環境変数になります。
詳しくはこちら

template.yaml

AWSTemplateFormatVersion: "2010-09-09"
Transform: "AWS::Serverless-2016-10-31"
Resources:
  NodeLayer:
    Type: "AWS::Serverless::LayerVersion"
    Properties:
      LayerName: NodeLibraryLayer
      ContentUri: layers/
      CompatibleRuntimes:
        - nodejs14.x
      RetentionPolicy: Delete
  TestFunction:
    Type: "AWS::Serverless::Function"
    Properties:
      FunctionName: testFunction
      Handler: index.handler
      Runtime: nodejs14.x
      CodeUri: src/functions/test
      Layers:
        - !Ref NodeLayer

Layer側

ResourceにNodeLayerという名前でServerless LayerVersionを指定しています。
・ContentUriはnodejsが存在するディレクトリを指定します。
・CompatibleRuntimesは基本的にLambda側と同じversionを指定しておけば良いです。
・RetentionPolicyはLambda Layerがデフォルトでcloudformationが更新さるとversion管理される。Deleteに設定するとスタックが作られたタイミングで最新のLayerだけが残り、過去versionは削除される設定になる。

Lambda側

  Layers:
    - !Ref NodeLayer

ここでLayerをNodeLayerと指定しています。
!Refでtemplate内で定義した名前を利用出来ます。
Ref関数

.gitignore

開発環境によってはよしなにやってくれるかもですが、node_modulesがコミット対象になっていたらいつもどおり.gitignoreを作成しましょう。

node_modules

そしたらコミット&pushで完了です。

確認作業

パイプラインも成功しています。

無事スタックが作成(更新)されています。

同時にlambdaも生成されていますね。 layerに(1)とあり、下の方にスクロールするとレイヤーが追加されていることがわかります。

lambda関数をテストで実行してみます。

ログ出力でuuidを出力していることがわかります。

これでライブラリを含むPipelineとcloudformationを使ったデプロイは完了です。

コメントを残す

メールアドレスが公開されることはありません。 * が付いている欄は必須項目です