LoginSignup
13
0

More than 3 years have passed since last update.

Serverless Framework(APIGateWay+Lambda+DynamoDB)でのリダイレクト

Last updated at Posted at 2018-12-20

要件

pathパラメータをキーにDynamoDBに格納されているURLへリダイレクトさせる。

アーキテクチャ

architecture.png

2018/11/05にAPIGatewayでWAFを有効化できるようになりました(ワーイ)

APIGateway設定

新規作成

apigatewaynew.png

※ちょうど先日(2018/12/18)APIGatewayで WebSocketAPI の構築が出来るようになったのですが、そこには今回触れません:bow_tone1:

パスパラメータの設定

リソースのアクション→リソースの作成
pathparameter.png

メソッドの設定(GET)

リソースのアクション→メソッドの作成
method.png

Lambda プロキシ統合 はAPIGatewayに対するリクエストの情報をよしなにまとめてLambdaに渡してくれるの非常に便利です!!!

メソッド作成後

method_2.png

Lambda

handler.py
import json
import boto3
from boto3.dynamodb.conditions import Key, Attr

DYNAMO_TABLE_NAME = 'hoge-dynamodb'

def hoge(event, context):
    path_id = event['pathParameters']['Id']

    # DBConnection
    dynamodb = boto3.resource('dynamodb')
    table = dynamodb.Table(DYNAMO_TABLE_NAME)

    partition_key = {"Id": path_id}
    res = table.get_item(Key=partition_key)
    item = res["Item"]
    result = {
        "statusCode": 302,
        "headers": {
            "Location": item['url']
        },
        "body": ''
    }
    return result

Lambda プロキシ統合 を設定した場合はlambdaからのレスポンス形式に注意が必要です :warning:

DynamoDB

新規テーブル作成

dynamodb.png

項目の追加

dynamodb-item.png

Serverless設定

serverless.yml
service: redirect
frameworkVersion: ">=1.1.0 <2.0.0"

custom:
  pythonRequirements:
    dockerizePip: true

provider:
  name: aws
  runtime: python3.6
  stage: dev
  region: ap-northeast-1
  profile: hoge-profile
  environment:
    STAGE: ${self:provider.stage}
  iamRoleStatements:
    - Effect: Allow
      Action:
        - dynamodb:*
      Resource: "arn:aws:dynamodb:${self:provider.region}:*:table/*"

functions:
  redirect:
    handler: handler.hoge
    events:
      - http:
          method: get
          path: /{Id}
          integration: lambda-proxy

resources:
  Resources:
    RedirectDynamoDbTable:
      Type: AWS::DynamoDB::Table
      DeletionPolicy: Retain
      Properties:
        TableName: hoge-dynamodb
        AttributeDefinitions:
          -
            AttributeName: Id
            AttributeType: S
        KeySchema:
          -
            AttributeName: Id
            KeyType: HASH
        ProvisionedThroughput:
          ReadCapacityUnits: 1
          WriteCapacityUnits: 1

デプロイ

$ sls deploy -v

確認

APIGateWayにデプロイされたエンドポイントにpathパラメータをDynamoDBに挿入した hogepath を付与してアクセスします。
https://xxxxxxxx.execute-api.ap-northeast-1.amazonaws.com/dev/hogepath

無事にリダイレクトされたら成功です:confetti_ball:

実行環境

macOS Mojave 10.14
serverless 1.35.1
npm 6.5.0

ハマったポイント

ServerlessでDynamoDBのキャパシティユニットを設定しなくてもデフォルト値が入るだろうと記載しないでデプロイしたらCloudFormationのエラーにハマって一日潰しました・・・:sob:

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