使用 SAM 创建 API 密钥和使用计划

Create an API Key and Usage Plan with SAM

我正在学习 AWS SAM,但无法找到有关如何通过 SAM 模板创建 API 密钥和使用计划的信息。

AWSTemplateFormatVersion: '2010-09-09'
Transform: AWS::Serverless-2016-10-31

Resources:
  GetFamilyByIdFunction:
    Type: AWS::Serverless::Function
    Properties:
      Runtime: nodejs8.10
      Handler: get-family-by-id.handler
      CodeUri: get-family-by-id/
      Timeout: 300
      Events:
        GetFamilyByIdApi:
          Type: Api
          Properties:
            Path: "/family/{id}"
            Method: get

我想创建一个 API 密钥并将其与上面指定的 'GetFamilyByIdApi' 的使用计划相关联。任何帮助将不胜感激。

经过一番挖掘,我明白了。当您想要自己定义 api 键的值而不是让 API 网关生成值时,可以使用此解决方案。我假设存在一个变体。请注意,'HvgnApi' 指的是我的 Swagger 定义(类型:AWS::Serverless::Api)。享受吧!

  ApiKey: 
    Type: AWS::ApiGateway::ApiKey
    Properties: 
      Name: !Join ["", [{"Ref": "AWS::StackName"}, "-apikey"]]
      Description: "CloudFormation API Key V1"
      Enabled: true
      GenerateDistinctId: false
      Value: abcdefg123456
      StageKeys:
        - RestApiId: !Ref HvgnApi
          StageName: prod

  ApiUsagePlan:
    Type: "AWS::ApiGateway::UsagePlan"
    Properties:
      ApiStages: 
        - ApiId: !Ref HvgnApi
          Stage: prod     
      Description: !Join [" ", [{"Ref": "AWS::StackName"}, "usage plan"]]
      Quota:
        Limit: 1000
        Period: MONTH
      UsagePlanName: !Join ["", [{"Ref": "AWS::StackName"}, "-usage-plan"]]

  ApiUsagePlanKey:
    Type: "AWS::ApiGateway::UsagePlanKey"
    DependsOn: 
      - HvgnApi
    Properties:
      KeyId: !Ref ApiKey
      KeyType: API_KEY
      UsagePlanId: !Ref ApiUsagePlan