我正在使用 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
documentation 指定的 UsagePlan
部分创建了一个 ApiKey
、一个 UsagePlan
和一个 ApiUsagePlan
(即键和使用计划)。
好的。现在,在稍后的步骤中,我需要调用此 API,因此我需要 Cognito 凭据,即我的 Cognito 用户名和密码(好吧,这是我自己创建帐户后获得的,就像普通用户一样),然后我还需要Api Key。现在我应该如何检索它?首先是作为开发者,还是未来的普通用户?
我无法通过 YAML 模板中的 Output
检索它。我尝试了很多东西,也读了很多。这对于 SAM 来说是不可能的。
我可以使用 boto3 来获取 UsagePlan id、ApiKey id 和最后的 UsagePlanKey。但这对我来说似乎很奇怪,因为它要求我浏览帐户中所有现有的使用计划和 Api 密钥。并且由于这些资源是由 SAM 创建的......实际上没有一种逻辑可以用来理解我应该采用哪一种。对于 UsagePlan 我可以,因为我决定了它的名字......但不是 ApiKey。
那么我如何以“正常”或“最先进”的方式有效地检索 SAM 创建的资源 ID(ApiKey、UsagePlan、UsagePlanKey)?
感谢您的支持
答案 0 :(得分: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
也许是这样的:
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