首页 > 解决方案 > 使用 SAM 创建 API 密钥和使用计划

问题描述

我正在学习 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”的使用计划相关联。任何帮助,将不胜感激。

标签: amazon-web-servicesaws-sam

解决方案


After a bit of digging I figured it out. This solution is when you want to define the value of the api key yourself as opposed to letting API Gateway generate a value. I assume a variation exists for that. Note that 'HvgnApi' refers to my Swagger definition (Type: AWS::Serverless::Api). Enjoy!

  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

推荐阅读