如何在 AWS CDK 中使用 API 网关部署中的现有阶段?

Int*_*ics 5 amazon-web-services typescript aws-api-gateway aws-cdk

我有一个包含资源和阶段的现有 API 网关。我正在通过 aws cdk 向它添加一个新资源。网关配置了 deploy:false,所以我必须手动为它创建一个新的部署。我可以导入网关,但是在 Stage 类中找不到类似的方法(fromLookup?)。我知道我可以创建一个新阶段,但这听起来不像是一个可扩展的解决方案。

代码如下:

const api = apigateway.RestApi.fromRestApiAttributes(this, 'RestApi', {
  restApiId: 'XXX',
  rootResourceId: 'YYYY',
});

const deployment = new apigateway.Deployment(this, 'APIGatewayDeployment', {
  api,
});

// How to get an existing stage here instead of creating a new one?
const stage = new apigateway.Stage(this, 'test_stage', {
  deployment,
  stageName: 'dev',
});

api.deploymentStage = stage;
Run Code Online (Sandbox Code Playgroud)

小智 6

我今天遇到了同样的问题,但我发现如果您为部署资源设置stageName属性,它将使用现有阶段。

如果您检查 Deployment 资源的 CloudFormation 文档,它具有 StageName 属性 ( https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-apigateway-deployment.html )。

但是,如果您检查 CDK 的部署实现,它不支持stageName属性(https://github.com/aws/aws-cdk/blob/master/packages/@aws-cdk/aws-apigateway/ lib/deployment.ts#L71),并通过遵循 Deployment 类的扩展,它最终从需要构造函数中的stageName值的CfnResource进行扩展。

因此,我最终通过执行以下操作强制部署资源选择我想要的值:

const api = apigateway.RestApi.fromRestApiAttributes(this, 'RestApi', {
  restApiId: 'XXX',
  rootResourceId: 'YYYY',
});

const deployment = new apigateway.Deployment(this, 'APIGatewayDeployment', {
  api,
});

deployment.resource.stageName = 'YourStageName';
Run Code Online (Sandbox Code Playgroud)

  • “资源”对我来说是 Deployment 对象的私有属性。Typescript 不会让它编译。 (2认同)