You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在AWS CDK中将现有UsagePlan关联到API Stage?

问题

CDK文档指出,可通过静态方法fromUsagePlanId导入外部UsagePlan,但该方法返回的IUsagePlan接口不具备addApiStage方法,无法关联自定义的API及其Stage。

现有代码片段:

import * as apigateway from 'aws-cdk-lib/aws-apigateway';

export class CdkApiGwTemplateStack extends cdk.Stack {
  constructor(scope: Construct, id: string, props?: cdk.StackProps) {
    super(scope, id, props);

    const api = new apigateway.RestApi(this,`${domain.toLowerCase()}-${subDomain.toLowerCase()}`,
      {
        restApiName: `${domain.toLowerCase()}-${subDomain.toLowerCase()}`,
        description: apiDescription,
        binaryMediaTypes: binaryMediaTypes,
        deployOptions: {
          accessLogDestination: new LogGroupLogDestination(logGroup),
          loggingLevel:
            cloudwatchLoggingLevel.toUpperCase() as MethodLoggingLevel,
          stageName: environment.toLowerCase(),
          variables: variables,
        },
      }
    );

    const key = api.addApiKey('ApiKey', {
      apiKeyName: apikeyName,
      description: apiKeyDescription,
    });

    const plan = apigateway.UsagePlan.fromUsagePlanId(this, 'getExternalUsagePlan', usagePlanId);

    plan.addApiKey(key);
}

曾尝试查找CloudFormation L1资源但未找到可行方案,需求是:通过IUsagePlan调用UsagePlan类的addApiStage方法,或找到其他方法将API关联到现有UsagePlan。

解决方案

IUsagePlan作为抽象接口,仅持有外部资源的引用,没有提供修改外部资源的方法,因此无法直接调用addApiStage。要实现API Stage与外部UsagePlan的关联,需使用CloudFormation L1资源CfnUsagePlan手动配置关联关系:

实现步骤

  1. 保留原有API和外部UsagePlan的创建/导入逻辑
  2. 通过CfnUsagePlan关联外部UsagePlan与目标API Stage,传入UsagePlan ID、API ID和Stage名称

修改后的代码示例

import * as apigateway from 'aws-cdk-lib/aws-apigateway';
import * as cdk from 'aws-cdk-lib';
import { Construct } from 'constructs';

export class CdkApiGwTemplateStack extends cdk.Stack {
  constructor(scope: Construct, id: string, props?: cdk.StackProps) {
    super(scope, id, props);

    // 原有API创建逻辑不变
    const api = new apigateway.RestApi(this,`${domain.toLowerCase()}-${subDomain.toLowerCase()}`,
      {
        restApiName: `${domain.toLowerCase()}-${subDomain.toLowerCase()}`,
        description: apiDescription,
        binaryMediaTypes: binaryMediaTypes,
        deployOptions: {
          accessLogDestination: new apigateway.LogGroupLogDestination(logGroup),
          loggingLevel:
            cloudwatchLoggingLevel.toUpperCase() as apigateway.MethodLoggingLevel,
          stageName: environment.toLowerCase(),
          variables: variables,
        },
      }
    );

    const key = api.addApiKey('ApiKey', {
      apiKeyName: apikeyName,
      description: apiKeyDescription,
    });

    // 导入外部UsagePlan
    const plan = apigateway.UsagePlan.fromUsagePlanId(this, 'getExternalUsagePlan', usagePlanId);

    // 保留API Key关联逻辑
    plan.addApiKey(key);

    // 用L1资源关联API Stage到外部UsagePlan
    new apigateway.CfnUsagePlan(this, 'AssociateApiStageToUsagePlan', {
      usagePlanId: plan.usagePlanId,
      apiStages: [
        {
          apiId: api.restApiId,
          stage: api.deploymentStage.stageName,
          // 可选:添加该Stage的专属配额/速率限制
          // throttle: { rateLimit: 100, burstLimit: 200 },
          // quota: { limit: 1000, period: 'MONTH' }
        },
      ],
    });
  }
}

注意事项

  • 确保当前CDK执行角色拥有修改目标外部UsagePlan的权限
  • 该操作会追加新的API Stage关联,不会覆盖UsagePlan中原有的关联配置
  • 若需为该Stage设置单独的配额或速率限制,可在apiStages对象中添加throttle或quota属性

内容的提问来源于stack exchange,提问作者Leandro Ocampo Rendón

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.06 12:35:26