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

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


要件

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 プロキシ統合 を設定した場合はlamdbaからのレスポンス形式に注意が必要です :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:

コメント

このブログの人気の投稿

投稿時間:2021-06-17 05:05:34 RSSフィード2021-06-17 05:00 分まとめ(1274件)

投稿時間:2021-06-20 02:06:12 RSSフィード2021-06-20 02:00 分まとめ(3871件)

投稿時間:2020-12-01 09:41:49 RSSフィード2020-12-01 09:00 分まとめ(69件)