如何使用 AWS CDK 查找现有的 ApiGateway

How to use AWS CDK to look up existing ApiGateway

我正在使用 AWS CDK 构建我的 lambda,我想从 lambda 的 CDK 堆栈注册端点。

我发现我可以使用 fromRestApiId(scope, id, restApiId) 获取现有的 ApiGateway 构造 (documentation here)

所以目前这个效果很好:

    //TODO how to look up by ARN instead of restApiId and rootResourceId??
    const lambdaApi = apiGateway.LambdaRestApi
                                .fromRestApiAttributes(this, generateConstructName("api-gateway"), {
                                    restApiId: <API_GATEWAY_ID>,
                                    rootResourceId: <API_GATEWAY_ROOT_RESOURCE_ID>,
                                });

    const lambdaApiIntegration = new apiGateway.LambdaIntegration(lambdaFunction,{
        proxy: true,
        allowTestInvoke: true,
    })

    const root = lambdaApi.root;

    root.resourceForPath("/v1/meeting/health")
        .addMethod("GET", lambdaApiIntegration);

但我想部署到许多 AWS 账户和许多区域。我不想为每个帐户-区域对硬编码 API_GATEWAY_IDAPI_GATEWAY_ROOT_RESOURCE_ID

是否有更通用的方法来获取现有的 ApiGateway 构造(例如,通过名称或 ARN)?

提前致谢。

让我们用一个资源

做一个简单的Api
const restApi = new apigw.RestApi(this, "my-api", {
  restApiName: `my-api`,
});
const mockIntegration = new apigw.MockIntegration();
const someResource = new apigw.Resource(this, "new-resource", {
  parent: restApi.root,
  pathPart: "somePath",
  defaultIntegration: mockIntegration,
});
someResource.addMethod("GET", mockIntegration);

假设我们想在另一个堆栈中使用这个 api 和资源,我们首先需要导出

new cdk.CfnOutput(this, `my-api-export`, {
  exportName: `my-api-id`,
  value: restApi.restApiId,
});

new cdk.CfnOutput(this, `my-api-somepath-export`, {
  exportName: `my-api-somepath-resource-id`,
  value: someResource.resourceId,
});

现在我们需要导入新的堆栈

const restApi = apigw.RestApi.fromRestApiAttributes(this, "my-api", {
  restApiId: cdk.Fn.importValue(`my-api-id`),
  rootResourceId: cdk.Fn.importValue(`my-api-somepath-resource-id`),
});

并简单地添加额外的资源和方法。

const mockIntegration = new apigw.MockIntegration();
new apigw.Resource(this, "new-resource", {
  parent: restApi.root,
  pathPart: "new",
  defaultIntegration: mockIntegration,
});