将Custom Resource 添加到您的 CDK 堆栈。正如CloudFormation docs 所说,
自定义资源使您能够编写自定义预置逻辑...... AWS CloudFormation 在您创建、更新(如果您更改了自定义资源)或删除堆栈时运行。
换句话说,每次堆栈的 API 定义更改时,您都可以将 API 客户端 SDK 本地提取到存储桶中。
您定义一个 lambda,它使用 apigateway 和 s3 SDK 客户端生成 API 客户端 .zip 输出并将其保存到存储桶中。然后是你
将其与custom resource logic 集成到stack lifecycle events 中。
CloudFormation 处理在 create-update-delete 和响应上调用 lambda。
(注意:术语“自定义资源”可能会令人困惑。是的,它们可以帮助填补 CDK/CloudFormation 的空白
使用 API 调用实际创建基础设施资源。但是CustomResource 没有
必须创建任何基础设施。它们用于查找、运行测试和播种初始数据。你能做什么取决于你的 lambda。)
aws-cdk-samples has an example 的自定义资源实现。以下是您的用例的自定义资源管道框架:
export class ExportApigCustomResource extends Construct {
constructor(scope: Construct, id: string, props: ExportApigCustomResourceProps) {
super(scope, id);
// the provider handles the orchestration
// https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib-readme.html#custom-resource-providers
const provider = new cr.Provider(this, 'Provider', {
// CloudFormation will call this lambda on create-update-delete
onEventHandler: new lambda.NodejsFunction(this, 'ExportApigLambda', {
entry: path.join(__dirname, 'exportApi.ts'),
role: new iam.Role(this, 'CrLambdaRole', {...add the right policies});
})
});
// information for the getSdk call that is passed to the lambda in the triggered lifecycle events
// use a strongly typed input type for safety
const properties: ExportApigCustomResourceProperties = {
restApiId: props.api.restApiId,
bucketName: props.bucket.bucketName,
stageName: 'prod',
sdkType: 'javascript',
};
// the actual custom resource
// https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.CustomResource.html
new cdk.CustomResource(this, 'Resource', {
resourceType: 'Custom::ExportApi',
serviceToken: provider.serviceToken,
properties,
});
}
}
自定义资源的设置很繁琐。但它们在 CDK 中得到了很好的支持,并且是一种将配置逻辑与基础架构代码保持在同一位置的优雅方式。