Cloudformation 创建apikey

什么是apikey

A resource that can be distributed to callers for executing Method resources that require an API key. API keys can be mapped to any Stage on any RestApi, which indicates that the callers with the API key can make requests to that stage.

用Cloudformation 创建并管理apikey

Resources:
    MyApiKey:
      Type: AWS::ApiGateway::ApiKey
      Properties:
        # CustomerId: String
        # Description: String
        Enabled: true
        # Name: ${env:SCOPE}-${env:VERSION}-apikey
        # StageKeys:
          # - StageKey
        Value: ${env:API_KEY}

    MyUsagePlan:
      Type: AWS::ApiGateway::UsagePlan
      Properties:
        ApiStages:
          - ApiId:
              Fn::Select: [0, Fn::Split: [".", "${ssm:/service/${env:SCOPE}/${env:VERSION}/recruiting-seminar-service}"]]
            Stage: dev
          - ApiId:
              Fn::Select: [0, Fn::Split: [".", "${ssm:/service/${env:SCOPE}/${env:VERSION}/recruiting-interview-service}"]]
            Stage: dev
          - ApiId:
              Fn::Select: [0, Fn::Split: [".", "${ssm:/service/${env:SCOPE}/${env:VERSION}/recruiting-channel-service}"]]
            Stage: dev
          - ApiId:
              Fn::Select: [0, Fn::Split: [".", "${ssm:/service/${env:SCOPE}/${env:VERSION}/recruiting-onboarding-service}"]]
            Stage: dev
          - ApiId:
              Fn::Select: [0, Fn::Split: [".", "${ssm:/service/${env:SCOPE}/${env:VERSION}/recruiting-document-submission-service}"]]
            Stage: dev
          - ApiId:
              Fn::Select: [0, Fn::Split: [".", "${ssm:/service/${env:SCOPE}/${env:VERSION}/recruiting-user-service}"]]
            Stage: dev
        Description: String
        # Quota:
        #   QuotaSettings
        # Throttle:
        #   ThrottleSettings
        UsagePlanName: ${env:SCOPE}-${env:VERSION}-useagePlan
    MyUsagePlanKey:
      Type: AWS::ApiGateway::UsagePlanKey
      Properties:
        KeyId:
          Ref: MyApiKey
        KeyType: API_KEY
        UsagePlanId:
          Ref: MyUsagePlan


Outputs:
  MyApiKeyId:
    Value:
      Ref: MyApiKey

遇到两个坑

  1. 不同名字的api key 的值不能相同, 否则会创建失败.
Serverless Error ---------------------------------------
 
  An error occurred: MyApiKey - API Key already exists (Service: AmazonApiGateway; Status Code: 409; Error Code: ConflictException; Request ID: 6b292def-9176-11e9-a391-3f5b37776e47).
 
  Stack Trace --------------------------------------------

解决办法: 不同的环境创建不同的key值

  1. 不能直接更新api key的值, 如果需要更新, 需要将api key的名字修改一下.

CloudFormation cannot update a stack when a custom-named resource requires replacing. Rename jill-v1-apikey and update the stack again..

解决办法: 不指定api key的Name 属性, 这样每次在update的时候,会自动重新生成一个Name, 如: jill-MyApi-W6VNP6FTR5ZJ

参考资料:

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。