如何使用 AWS CDK 查找现有 ApiGateway

2023-11-21

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

我发现我可以使用 fromRestApiId(scope, id, restApiId) 获取现有的 ApiGateway 构造 (文档在这里)

所以目前这效果很好:

    //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_ID or API_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,
});
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何使用 AWS CDK 查找现有 ApiGateway 的相关文章

随机推荐