簡體   English   中英

如何在 AWS CDK 中使用 API 網關部署中的現有階段?

[英]How to use an existing stage in API Gateway deployments in 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;

我今天面臨同樣的問題,但我發現如果您為部署資源設置stageName屬性,它將使用現有階段。

如果您檢查部署資源的 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';

對我來說,問題是部署更新了 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時部署更新,即使沒有進行其他更改

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM