【问题标题】:Deploy multiple API Gateway stages with AWS CDK使用 AWS CDK 部署多个 API Gateway 阶段
【发布时间】:2020-06-18 11:40:34
【问题描述】:

API Gateway 有阶段的概念(例如:dev、test、prod),通过 AWS 控制台部署多个阶段非常简单。

是否可以使用 AWS CDK 定义和部署多个阶段?

我已经尝试过,但到目前为止似乎不可能。以下是一个非常基本的堆栈的精简示例,该堆栈构造了一个 API 网关 RestApi 以服务于 lambda 函数:

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

    // Define stage at deploy time; e.g: STAGE=prod cdk deploy
    const STAGE = process.env.STAGE || 'dev'

    // First, create a test lambda
    const testLambda = new apilambda.Function(this, 'test_lambda', {
      runtime: apilambda.Runtime.NODEJS_10_X,    
      code: apilambda.Code.fromAsset('lambda'),  
      handler: 'test.handler',
      environment: { STAGE }
    })

    // Then, create the API construct, integrate with lambda and define a catch-all method
    const api = new apigw.RestApi(this, 'test_api', { deploy: false });
    const integration = new apigw.LambdaIntegration(testLambda);

    api.root.addMethod('ANY', integration)

    // Then create an explicit Deployment construct
    const deployment  = new apigw.Deployment(this, 'test_deployment', { api });

    // And, a Stage construct
    const stage = new apigw.Stage(this, 'test_stage', { 
      deployment,
      stageName: STAGE
    });

    // There doesn't seem to be a way to add more than one stage...
    api.deploymentStage = stage
  }
}

我没有使用LambdaRestApi,因为存在不允许显式Deployment 的错误,这显然是显式定义Stage 所必需的。这种方法需要额外的LambdaIntegration 步骤。

这个堆栈运行良好——我可以部署一个新堆栈并使用环境变量定义 API Gateway 阶段;例如:STAGE=my_stack_name cdk deploy.

我希望这可以让我通过执行以下操作来添加阶段:

STAGE=test cdk deploy
STAGE=prod cdk deploy
# etc.

但是,这不起作用 - 在上面的示例中,test 阶段被 prod 阶段覆盖。

在尝试上述方法之前,我认为可以简单地创建一个或多个 Stage 构造对象并将它们分配给同一个部署(它已经将 RestApi 作为参数)。

但是,必须通过api.deploymentStage = stage 为 api 显式分配一个阶段,并且看起来只能分配一个。

这意味着这是不可能的,相反,您必须为 test、prod 等创建不同的堆栈。这意味着相同 API 网关和 Lambda 函数的多个实例。

更新

经过进一步的修改,我发现似乎可以部署多个阶段,尽管我还没有完全摆脱困境......

首先,恢复RestApi 的默认行为——删除自动创建Deployment 的prop deploy: false:

const api = new apigw.RestApi(this, 'test_api');

然后,像以前一样,创建一个显式的Deployment 构造:

const deployment  = new apigw.Deployment(this, 'test_deployment', { api });

此时,请务必注意prod 阶段已定义,如果您为prod 显式创建Stage 构造,cdk deploy 将失败。

相反,为您要创建的每个其他阶段创建一个Stage 构造;例如:

new apigw.Stage(this, 'stage_test', { deployment, stageName: 'test' });
new apigw.Stage(this, 'stage_dev', { deployment, stageName: 'dev' });
// etc.

这部署和prod 按预期工作。但是,test 和 dev 都将失败,并出现 500 Internal Server Error 和以下错误消息:

由于配置错误,执行失败:Lambda 函数的权限无效

在 AWS 控制台中手动重新分配 lambda 会应用权限。我还没有弄清楚如何在 CDK 中解决这个问题。

【问题讨论】:

    标签: aws-api-gateway aws-cdk


    【解决方案1】:

    这应该可以解决问题。请注意,我已将资源从 test_lambda 重命名为 my_lambda 以避免与舞台名称混淆。另请注意,为简洁起见,我已将 environment 变量删除为 lambda。

    import * as cdk from '@aws-cdk/core';
    import * as apigw from '@aws-cdk/aws-apigateway';
    import * as lambda from '@aws-cdk/aws-lambda';
    import { ServicePrincipal } from '@aws-cdk/aws-iam';
    
    export class ApigwDemoStack extends cdk.Stack {
      constructor(scope: cdk.Construct, id: string, props?: cdk.StackProps) {
        super(scope, id, props);
    
        // First, create a test lambda
        const myLambda = new lambda.Function(this, 'my_lambda', {
          runtime: lambda.Runtime.NODEJS_10_X,    
          code: lambda.Code.fromAsset('lambda'),  
          handler: 'test.handler'
        });
    
        // IMPORTANT: Lambda grant invoke to APIGateway
        myLambda.grantInvoke(new ServicePrincipal('apigateway.amazonaws.com'));
    
        // Then, create the API construct, integrate with lambda
        const api = new apigw.RestApi(this, 'my_api', { deploy: false });
        const integration = new apigw.LambdaIntegration(myLambda);
        api.root.addMethod('ANY', integration)
    
        // Then create an explicit Deployment construct
        const deployment  = new apigw.Deployment(this, 'my_deployment', { api });
    
        // And different stages
        const [devStage, testStage, prodStage] = ['dev', 'test', 'prod'].map(item => 
          new apigw.Stage(this, `${item}_stage`, { deployment, stageName: item }));
    
        api.deploymentStage = prodStage
      }
    }
    

    这里需要注意的重要部分是:

    myLambda.grantInvoke(new ServicePrincipal('apigateway.amazonaws.com'));
    

    显式授予对 API 网关的调用访问权限允许所有其他阶段(不直接与 API 关联)不会引发以下错误:

    Execution failed due to configuration error: Invalid permissions on Lambda function
    

    我必须通过从控制台显式创建另一个阶段并启用日志跟踪来对其进行测试。 api 和 stage 的 API Gateway 执行日志会捕获此特定错误。

    我自己对此进行了测试。这应该可以解决您的问题。我建议完全创建一个新堆栈来测试这一点。

    我的超级简单的 Lambda 代码:

    // lambda/test.ts
    export const handler = async (event: any = {}) : Promise <any> => {
      console.log("Inside Lambda");
      return { 
        statusCode: 200, 
        body: 'Successfully Invoked Lambda through API Gateway'
      };
    }
    

    【讨论】:

    • 好问题。我认为缺少细节是因为api.deploymentStage = prodStage 负责隐式授予调用,因此我们最终只能对一个阶段进行适当的调用访问。如果RestApi 可以提供同时提供多个阶段的方法,那么grantInvoke 将不会被明确要求。 api.deploymentStages = [prodStage, devStage, testStage] 可能会有所帮助。
    • 酷,感谢您的更新。很好的答案,从中学到了很多!
    • @DarraghEnright AWS 今天发布了 AWS Solutions Construct。看看你是否可以利用他们的任何高阶构造docs.aws.amazon.com/solutions/latest/constructs/…
    • 感谢您的回答,但我遇到了另一个关于此问题的问题。当为所有创建的阶段分配相同的部署变量(类部署)时,使它们都接收到最新的部署结构。提供的问题是,其中一个阶段(例如“开发”)将接收最新部署,而其他 2 个将保留在其实际部署中。这样就可以将生产保持在稳定的结构中,并继续为开发或测试阶段进行发布,以便可以在不影响生产阶段的情况下对其进行测试。
    • 这是否意味着所有阶段都指向同一个 lambda?
    猜你喜欢
    • 1970-01-01
    • 2018-11-12
    • 1970-01-01
    • 2021-01-29
    • 2018-12-26
    • 1970-01-01
    • 2020-04-30
    • 2021-09-15
    • 2021-07-23
    相关资源
    最近更新 更多