kawabatas技術ブログ

試してみたことを書いていきます

sam で swagger.yaml を使う

概要

sam で swagger.yaml を使う時にハマったのでメモ。

コード

template.yaml

AWSTemplateFormatVersion: '2010-09-09'
Transform: AWS::Serverless-2016-10-31
Description: >
  sam-app
  
  Sample SAM Template for sam-app

# More info about Globals: https://github.com/awslabs/serverless-application-model/blob/master/docs/globals.rst
Globals:
  Function:
    Runtime: go1.x
    Timeout: 30

Resources:
  HelloWorldFunction:
    Type: AWS::Serverless::Function # More info about Function Resource: https://github.com/awslabs/serverless-application-model/blob/master/versions/2016-10-31.md#awsserverlessfunction
    Properties:
      CodeUri: hello-world/
      Handler: hello-world
      Role: !Sub "arn:aws:iam::${AWS::AccountId}:role/<ロール名>"
      Tracing: Active # https://docs.aws.amazon.com/lambda/latest/dg/lambda-x-ray.html
      Events:
        CatchAll:
          Type: Api # More info about API Event Source: https://github.com/awslabs/serverless-application-model/blob/master/versions/2016-10-31.md#api
          Properties:
            Path: /hello
            Method: GET
            RestApiId: !Ref ApiGateway

  ApiGateway:
    Type: AWS::Serverless::Api
    Properties:
      EndpointConfiguration: REGIONAL
      StageName: Prod
      DefinitionBody:
        'Fn::Transform':
          Name: 'AWS::Include'
          Parameters:
            Location: swagger.yaml

swagger.yaml

---
swagger: "2.0"
info:
  title: ""
basePath: "/Prod"
schemes:
- "https"
paths:
  /hello:
    get:
      responses: {}
      x-amazon-apigateway-integration:
        uri:
          Fn::Sub: "arn:aws:apigateway:${AWS::Region}:lambda:path/2015-03-31/functions/${HelloWorldFunction.Arn}/invocations"
        passthroughBehavior: "when_no_match"
        httpMethod: "POST"
        type: "aws_proxy"

# apigateway リソースポリシーの設定
x-amazon-apigateway-policy:
  Version: "2012-10-17"
  Statement:
  - Effect: "Deny"
    Principal: "*"
    Action: "execute-api:Invoke"
    Resource:
      Fn::Sub: "arn:aws:execute-api:${AWS::Region}:${AWS::AccountId}:*/*"
    Condition:
      StringNotEqualsIfExists:
        aws:sourceVpce: "<VPCエンドポイントID>"
  - Effect: "Allow"
    Principal: "*"
    Action: "execute-api:Invoke"
    Resource:
      Fn::Sub: "arn:aws:execute-api:${AWS::Region}:${AWS::AccountId}:*/*"

swagger は API Gateway を設定してからステージのエクスポートでファイルを作成していた。

f:id:kawabatas:20190123142904p:plain

template.yamlDefinitionBody と swagger.yamlx-amazon-apigateway-integration: uri: Fn::Sub: XXX がポイント。

参考

公式のexample