makes-trail / application-sample

アプリ開発準備
0 stars 0 forks source link

技術検証 - Serverless FrameworkでLambda関数をデプロイ #13

Closed kawabata2018 closed 3 years ago

kawabata2018 commented 3 years ago

背景

To do

完了条件

kawabata2018 commented 3 years ago

参考記事

kawabata2018 commented 3 years ago
service: mt-sample

provider:
  name: aws
  runtime: python3.8
  lambdaHashingVersion: 20201221
  stage: ${opt:stage, 'dev'}
  region: us-west-2
  logRetentionInDays: 30
  versionFunctions: false
  timeout: 20
  deploymentBucket:
    name: mt-sample-${self:provider.stage}-deployment

package:
  individually: true

custom:
  dynamedbTableName: mt-sample-dev

layers:
  requirements:
    package:
      artifact: layers/artifact/requirements.zip
    compatibleRuntimes:
      - python3.8
    retain: false

functions:
  hello:
    handler: handler.hello
    package:
      exclude:
        - '**'
      include:
        - handler.py
  fetch-openbd-summary:
    handler: main.handler
    layers:
      - {Ref: RequirementsLambdaLayer}
    package:
      artifact: functions/artifact/fetch_openbd_summary.zip
  save-openbd-to-ddb:
    handler: main.handler
    layers:
      - {Ref: RequirementsLambdaLayer}
    environment:
      DYNAMODB_TABLE: ${self:custom.dynamedbTableName}
    package:
      artifact: functions/artifact/save_openbd_to_ddb.zip

resources:
  Resources:
    DynamoDBIamPolicy:
      Type: AWS::IAM::Policy
      Properties:
        PolicyName: lambda-dynamodb
        PolicyDocument:
          Version: '2012-10-17'
          Statement:
            - Effect: Allow
              Action:
                - dynamodb:Query
                - dynamodb:Scan
                - dynamodb:GetItem
                - dynamodb:PutItem
                - dynamodb:UpdateItem
                - dynamodb:DeleteItem
              Resource: arn:aws:dynamodb:*:*:table/*
        Roles:
          - Ref: IamRoleLambdaExecution
kawabata2018 commented 3 years ago

Lambdaレイヤーをパッケージ化(zip化)するshellコマンド

フォルダにあるrequirements.txtをもとにPyPIパッケージをインストール・配置し、zipに圧縮する

#!/bin/sh

curdir=$(pwd)

for path in ./*; do
    echo $path

    if [[ -f $path || $path == *artifact ]]; then
        echo " => skip"
        continue
    fi

    # prepare a temporary directory
    tempdir=$(mktemp -d) && echo "created $tempdir"
    mkdir "$tempdir/python"
    cp -rf $path "$tempdir/python"
    cd $tempdir

    # install packages into python directory then zip it
    cd python
    docker run --rm -v $(pwd):/var/task -w /var/task lambci/lambda:build-python3.8 \
        pip install -r "$(basename $path)/requirements.txt" -t .

    cd ..
    zip -r9 "$(basename $path).zip" python && mv "$(basename $path).zip" "$curdir/artifact"

    rm -rf $tempdir && echo "removed $tempdir"

    cd $curdir
done
wait
kawabata2018 commented 3 years ago

24 にて完了