AWS CDK 使用构造函数中指定的逻辑 ID 生成 CF 模板资源的默认逻辑 ID。如果需要保留特定的逻辑 ID,可以在构造函数中传入 ConstructProps
对象,将需要保留逻辑 ID 的属性设置为 retainLogicalIds
,例如:
import { Construct } from 'constructs';
import { Stack, StackProps } from 'aws-cdk-lib';
import { CfnBucket } from 'aws-cdk-lib/aws-s3';
export class MyStack extends Stack {
constructor(scope: Construct, id: string, props?: StackProps) {
super(scope, id, props);
const bucket = new CfnBucket(this, 'MyBucket', {
bucketName: 'my-bucket',
});
// Retain the specific logical ID of the bucket
bucket.node.addMetadata('aws:cdk:logicalId', 'MyBucket');
}
}
在上述示例中,我们创建 CfnBucket
对象,并将其逻辑 ID 设置为 MyBucket
。通过 node.addMetadata
方法将逻辑 ID 附加到 bucket
对象上,这样在合成 CF 模板时就会保留这个逻辑 ID。