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

时间:2019-03-03 20:40:06

标签: amazon-web-services 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”的使用计划相关联。任何帮助将不胜感激。

1 个答案:

答案 0 :(得分:0)

经过一番挖掘,我发现了。当您要自己定义api密钥的值而不是让API Gateway生成值时,就可以使用此解决方案。我认为存在一个变化。请注意,“ 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