CDKTF(TypeScript) S3 Bucket非弃用参数代码示例请求
CDKTF + TypeScript S3后端(Bucket+DynamoDB锁)非弃用参数示例
以下是针对你提到的弃用参数的替代写法,直接给出完整可运行的代码和关键说明:
完整示例代码
import { Construct } from "constructs"; import { App, TerraformStack, TerraformBackend } from "cdktf"; import { AwsProvider, s3, dynamodb } from "@cdktf/provider-aws"; class S3BackendStack extends TerraformStack { constructor(scope: Construct, name: string) { super(scope, name); // 配置AWS Provider new AwsProvider(this, "AWS", { region: "us-east-1" }); // 创建Terraform状态存储用的S3 Bucket const backendBucket = new s3.S3Bucket(this, "TerraformStateBucket", { bucket: "your-unique-bucket-name-123", // 替换为你的全局唯一桶名 acl: "private", // 你已实现的非弃用ACL配置 // 非弃用版本控制配置 versioningConfiguration: [ { status: "Enabled" } ], // 非弃用服务端加密配置(直接嵌套在Bucket中) serverSideEncryptionConfiguration: [ { rule: [ { applyServerSideEncryptionByDefault: [ { sseAlgorithm: "AES256" // 如需KMS加密,替换为"aws:kms"并添加kmsMasterKeyId } ] } ] } ], // 防止Bucket被意外销毁的资源生命周期规则 lifecycle: { preventDestroy: true } }); // 非弃用的Bucket对象生命周期规则(自动清理旧状态版本) new s3.S3BucketLifecycleConfigurationV2(this, "BucketLifecycleRules", { bucket: backendBucket.id, rule: [ { id: "CleanupOldStateVersions", status: "Enabled", // 清理90天前的当前版本状态文件 expiration: { days: 90 }, // 清理30天前的旧版本状态文件 noncurrentVersionExpiration: { noncurrentDays: 30 } } ] }); // 创建DynamoDB锁表 const lockTable = new dynamodb.DynamodbTable(this, "TerraformLockTable", { name: "terraform-state-lock", billingMode: "PAY_PER_REQUEST", hashKey: "LockID", attribute: [ { name: "LockID", type: "S" } ], // 防止锁表被意外销毁 lifecycle: { preventDestroy: true } }); // 配置S3后端+DynamoDB锁 new TerraformBackend(this, "TerraformBackend", { backend: "s3", config: { bucket: backendBucket.bucket, key: "terraform/state.tfstate", region: "us-east-1", dynamodb_table: lockTable.name, encrypt: true } }); } } const app = new App(); new S3BackendStack(app, "s3-backend-stack"); app.synth();
关键参数替换说明
1. 版本控制(Versioning)
- 弃用写法:顶层
versioning参数(如versioning: { enabled: true }) - 非弃用写法:在
S3Bucket中使用versioningConfiguration嵌套块,通过status字段控制启用/暂停
2. 服务端加密(Server-Side Encryption)
- 弃用写法:顶层
serverSideEncryptionConfiguration参数 - 非弃用写法:直接在
S3Bucket内嵌套serverSideEncryptionConfiguration块,定义加密算法和密钥(如需KMS,补充kmsMasterKeyId)
3. 防止资源销毁(Prevent Destroy)
- 这个是Terraform通用的资源保护规则,直接在目标资源(Bucket、DynamoDB表)的
lifecycle属性中设置preventDestroy: true,避免terraform destroy误删核心资源
4. Bucket对象生命周期规则
- 弃用写法:顶层
lifecycle参数(用于配置对象过期/存储类过渡) - 非弃用写法:使用独立的
S3BucketLifecycleConfigurationV2资源,关联目标Bucket后定义具体规则(如旧版本清理、存储类转换等)
内容的提问来源于stack exchange,提问作者cumulus.ws
相关产品推荐
相关产品推荐

