【问题标题】:AWS SAM : How to retrieve implicitly created resources informationAWS SAM:如何检索隐式创建的资源信息
【发布时间】:2021-06-24 14:33:22
【问题描述】:

我正在使用 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 部分由documentation 指定,创建ApiKeyUsagePlanApiUsagePlan(即密钥和使用计划之间的关联)。

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

我无法通过 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


    【解决方案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 Key 值

    可能是这样的:

    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

    【讨论】:

    • 我确实喜欢你正确的 boto 方法。这些密钥应该保密并妥善保管
    • 确实,我按照你一开始提出的那样做了,但它在一定程度上违背了 SAM 的目的,即提出一种更直接(更少代码行)的资源定义方法。
    猜你喜欢
    • 2020-06-18
    • 2022-09-24
    • 2021-10-05
    • 1970-01-01
    • 2020-01-06
    • 1970-01-01
    • 2019-06-20
    • 2019-05-11
    • 1970-01-01
    相关资源
    最近更新 更多