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

时间:2020-09-18 06:08:19

标签: typescript amazon-web-services 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;

2 个答案:

答案 0 :(得分:2)

我今天也面临着同样的问题,但是我发现,如果为部署资源设置 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类的扩展,它会在从 CfnResource 扩展而来,该值在构造函数中期望为 stageName 值。

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

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

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

deployment.resource.stageName = 'YourStageName';

答案 1 :(得分:1)

对我来说,问题是部署更新了 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

使用您发布的代码,您应该在 Stage > Deployment History 选项卡中看到它不会添加新的部署,直到您为其提供唯一 ID。

注意:这可能并不理想,因为它会在您每次运行 cdk deploy 时部署更新,即使没有进行其他更改