AWS CDK创建跨区域APIGateway v2 Http Integration遇权限错误如何解决?
跨区域API Gateway v2与Lambda集成的CDK实现方案
问题原因
CDK默认会在API网关所在区域(示例中的ap-southeast-1)尝试创建Lambda权限资源,但跨区域Lambda(示例中的ap-southeast-3)无法在该区域被直接访问,因此抛出404 NotFound错误。
解决方案
1. 启用跨区域引用(Cross-Region References)
在CDK应用全局开启跨区域引用支持,CDK会自动处理跨区域资源的权限部署逻辑,将Lambda权限资源创建到Lambda所在区域而非API网关区域:
import { App } from 'aws-cdk-lib'; const app = new App({ crossRegionReferences: true, });
开启后,直接用fromFunctionArn加载跨区域Lambda并创建HttpLambdaIntegration即可正常工作。
2. 手动构造跨区域集成(替代方案)
若不想启用全局跨区域引用,可手动构造集成URI,跳过CDK自动创建权限的逻辑,再在Lambda所在区域手动添加调用权限:
步骤1:创建跨区域Http集成
import { HttpApi, HttpIntegration, HttpMethod, IntegrationType } from 'aws-cdk-lib/aws-apigatewayv2'; const crossRegionLambdaArn = 'arn:aws:lambda:ap-southeast-3:123456789012:function:your-cross-region-function'; // 构造跨区域Lambda的集成URI const integrationUri = `arn:aws:apigateway:ap-southeast-3:lambda:path/2015-03-31/functions/${crossRegionLambdaArn}/invocations`; const httpApi = new HttpApi(this, 'MyCrossRegionApi'); httpApi.addRoutes({ path: '/test', methods: [HttpMethod.GET], integration: new HttpIntegration(this, 'CrossRegionLambdaIntegration', { integrationUri, integrationType: IntegrationType.AWS_PROXY, }), });
步骤2:在Lambda所在区域添加调用权限
需要在Lambda所属区域(ap-southeast-3)的CDK栈中,创建Lambda权限允许API网关调用:
import { Function, Permission, ServicePrincipal } from 'aws-cdk-lib/aws-lambda'; const crossRegionLambda = Function.fromFunctionArn(this, 'TargetCrossRegionLambda', crossRegionLambdaArn); new Permission(this, 'ApiGatewayInvokePermission', { function: crossRegionLambda, principal: new ServicePrincipal('apigateway.amazonaws.com'), action: 'lambda:InvokeFunction', sourceArn: `arn:aws:execute-api:ap-southeast-1:123456789012:${httpApi.httpApiId}/*/*`, });
3. 注意事项
- 启用
crossRegionReferences后,CDK会自动创建跨区域同步用的S3桶,需确保账号具备S3相关权限。 - 手动配置权限时,需准确填写API网关的
sourceArn,包含正确的区域、账号ID和API ID。
内容的提问来源于stack exchange,提问作者slee
相关产品推荐
相关产品推荐

