AWS SAM:如何检索隐式创建的资源信息

问题描述 投票:0回答:2

我正在使用 AWS SAM 创建基础设施即代码。我当前的设置(仅进行学习测试)涉及 YAML SAM 模板中的这段代码:

API:
    Type: AWS::Serverless::Api
    Properties:
      StageName: !Sub ${Env}
      # Authentication on the API will be performed via a Key
      Auth:
        Authorizers:
            CognitoAuthorizer:
              UserPoolArn: !GetAtt CognitoUserPool.Arn
        DefaultAuthorizer : CognitoAuthorizer
        ApiKeyRequired: true 
        # this creates a key, a usage plan and associate them
        UsagePlan:
          CreateUsagePlan: PER_API
          UsagePlanName: !Sub ${Project}-${Env}-UsagePlan

文档
指定的UsagePlan部分创建了一个
ApiKey
、一个
UsagePlan
和一个
ApiUsagePlan
(即密钥和使用计划之间的关联)。

好的。现在,在后面的步骤中,我需要调用此 API,因此我需要 Cognito 凭据,即我的 Cognito 用户名和密码(好吧,自从我自己创建帐户以来,就像普通用户一样),我还需要 Api 密钥。现在我该如何取回它?首先作为开发者,但也为了未来的普通用户?

我无法通过 YAML 模板中的

Output
检索它。我尝试了很多事情,也读了很多书。这对于 SAM 来说是不可能的。

我可以使用 boto3 获取UsagePlan id、ApiKey id,最后获取UsagePlanKey。但这对我来说似乎很奇怪,因为它要求我检查帐户内所有现有的使用计划和 Api 密钥。由于这些资源是由 SAM 创建的...实际上没有一种逻辑可以用来理解我应该采用哪一个。对于UsagePlan,我可以,因为它的名称是我决定的……但对于ApiKey 则不行。

那么我如何以“正常”或“最先进”的方式有效地检索 SAM 创建的资源 ID(ApiKey、UsagePlan、UsagePlanKey)?

感谢您的支持

amazon-web-services aws-api-gateway boto3 aws-sam
2个回答
1
投票

考虑将

AWS::ApiGateway::ApiKey
资源添加到您的模板中,这是一个示例

MyApiKey:
  Type: AWS::ApiGateway::ApiKey
  Properties:
    Name: SomeApiKey
    Description: Some CloudFormation API Key V1
    Enabled: 'true'
    StageKeys:
      - RestApiId: !Ref API
        StageName: !Sub ${Env}

然后

sam build && sam deploy
,您应该能够在Outputs

中导出API密钥值

也许是这样的:

Outputs:
  MyApiKeyValue:
    Description: "the value of Some CloudFormation API Key V1"
    Value: !GetAtt MyApiKey.Value

有关 AWS::ApiGateway::ApiKey 的更多信息请参见此处:https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-apigateway-apikey.html


0
投票

不知何故很难用谷歌搜索,但您确实可以访问在幕后为API网关创建的逻辑资源,包括使用计划及其密钥。

给出 RestApi 的定义如下:

Resources
  RestApi:
    Type: AWS::Serverless::Api
    Properties:
      # ...
      Auth:
        UsagePlan:
          # ...

您可以使用参考

RestApi.UsagePlanKey
访问关联的使用计划密钥的ID。您可以根据需要在其他资源或输出中使用它:

Outputs:
  UsagePlanKeyId:
    Value: !Ref RestApi.UsagePlanKey

请注意,您将无法直接从模板中获取密钥的实际值,这是 CFT (SAM) 的一个(可能与安全相关的)限制。

但是,给定 ID,您可以通过对 API 网关管理 API 的单个 API 调用(或使用客户端库)来访问该值。

使用计划密钥 ID 将采用以下格式:

<api key id>:<usage plan id>

您还可以使用

!Ref RestApi.ApiKey

单独获取 ApiKey id

有关使用计划上所有可用逻辑 ID,请参阅以下文档: https://docs.aws.amazon.com/serverless-application-model/latest/developerguide/sam-specation- generated-resources-api.html#sam-specation- generated-resources-api-usage-plan

© www.soinside.com 2019 - 2024. All rights reserved.