如何在AWS CDK中部署API Gateway时使用现有阶段(stage)?

7
我已经有一个包含资源和阶段的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;
2个回答

6
今天我遇到了同样的问题,但是我发现如果您为部署资源设置stageName属性,则会使用现有的阶段。
如果您查看CloudFormation文档中的Deployment资源,它具有StageName属性(https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-apigateway-deployment.html)。
但是,如果您检查CDK的Deployment实现,则不支持stageName属性(https://github.com/aws/aws-cdk/blob/master/packages/@aws-cdk/aws-apigateway/lib/deployment.ts#L71),通过对Deployment类的扩展,它最终会从一个期望在构造函数中提供stageName值的进行扩展。
因此,我最终通过以下方式强制Deployment资源选择我想要的值:
const api = apigateway.RestApi.fromRestApiAttributes(this, 'RestApi', {
  restApiId: 'XXX',
  rootResourceId: 'YYYY',
});

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

deployment.resource.stageName = 'YourStageName';

2
“resource” 是 Deployment 对象上的私有属性。TypeScript 不允许编译它。 - Connor
@Connor 这只适用于 TypeScript 的私有属性,TypeScript 类型仅在编译时进行评估。这意味着我们可以使用 (deployment as any).resource.stageName = 'YourStageName'; - samuba
如果有多个阶段,这会如何运作? - tvb
我已在 CDK 存储库中创建了一个 Feature Request:https://github.com/aws/aws-cdk/issues/25582 - Lucas Santos

3

对我来说,问题在于部署正在更新API的资源,但没有更新阶段。解决方法是每次创建一个新的部署ID:

// Create deployment with ID based on current date
const deployment = new apigw.Deployment(this, 'deployment-' + new Date().toISOString(), { api });
  
// Deploy to existing API & stage  
const stage = new apigw.Stage(this, 'stage-alpha', { deployment, stageName: 'alpha' });
api.deploymentStage = stage

使用您发布的代码,您应该在“阶段”>“部署历史记录”选项卡中看到它不会添加新的部署,除非您提供唯一的ID。
注意:这可能并不理想,因为每次运行“cdk deploy”时都会部署更新,即使没有进行其他更改。

1
我无法让它正常工作。Cloudformation 抱怨阶段已经存在(是的,这是有意的)。xxx|dev 已经存在于堆栈 arn:aws:cloudformation:xxx:xxx:stack/xxx/xxxx-b5de-11ec-a70b-0257aa684859 中。 - tvb
1
这会导致错误,因为新的apigw.Stage将始终尝试创建新阶段,即使阶段已存在。 - Maclean Pinto

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接