AWS SAM如何获取隐式创建的ApiKey、UsagePlan等资源信息
解决方案
方案1:直接通过SAM模板Output字段导出(最推荐)
SAM隐式创建的资源遵循固定的逻辑ID命名规则:针对你逻辑ID为API的AWS::Serverless::Api资源,对应的隐式资源逻辑ID分别为:
- ApiKey:
API.ApiKey - UsagePlan:
API.UsagePlan - UsagePlanKey:
API.UsagePlanKey
你可以直接在模板的Outputs段引用这些逻辑ID导出所需信息,示例如下:
Outputs: # 导出隐式创建的ApiKey ID AutoCreatedApiKeyId: Value: !Ref API.ApiKey # 导出ApiKey的明文值,可根据需要决定是否导出 AutoCreatedApiKeyValue: Value: !GetAtt API.ApiKey.Value # 导出隐式创建的UsagePlan ID AutoCreatedUsagePlanId: Value: !Ref API.UsagePlan # 导出隐式创建的UsagePlanKey ID AutoCreatedUsagePlanKeyId: Value: !Ref API.UsagePlanKey
修改模板后重新执行sam deploy,部署完成后即可在CloudFormation栈的输出页看到对应值,也可以通过AWS CLI或者SDK直接读取栈输出获取。
方案2:通过boto3精准查询(无需修改现有模板)
你不需要遍历账号下所有的API密钥,可通过UsagePlan和ApiKey的关联关系直接查询,步骤如下:
- 按你自定义的UsagePlan名称过滤查询,获取目标UsagePlan ID
- 调用APIGateway的
get_usage_plan_keys接口,直接查询该UsagePlan关联的所有ApiKey - 用获取到的ApiKey ID查询密钥的具体值
示例代码:
import boto3 apigw_client = boto3.client('apigateway') # 替换为你模板中定义的UsagePlanName实际值 usage_plan_name = "${Project}-${Env}-UsagePlan" # 按名称查询UsagePlan usage_plan_resp = apigw_client.get_usage_plans(nameQuery=usage_plan_name) usage_plan_id = usage_plan_resp['items'][0]['id'] # 查询该UsagePlan关联的ApiKey usage_plan_keys = apigw_client.get_usage_plan_keys(usagePlanId=usage_plan_id) api_key_id = usage_plan_keys['items'][0]['id'] # 查询ApiKey明文值 api_key_detail = apigw_client.get_api_key(apiKey=api_key_id, includeValue=True) api_key_value = api_key_detail['value'] print(f"UsagePlan ID: {usage_plan_id}") print(f"ApiKey ID: {api_key_id}") print(f"ApiKey值: {api_key_value}")
该方法查询效率极高,完全不需要遍历全量资源即可精准匹配到目标资源。
内容的提问来源于stack exchange,提问作者FenryrMKIII
相关产品推荐
相关产品推荐

