无法在 terraform 版本 4.5.0 中为多个 aws s3 添加 versioning_configuration

Unable to add versioning_configuration for multiple aws s3 in terraform version 4.5.0

尝试使用 Terraform 和下面提供的代码创建多个 AWS s3 存储桶。 提供商版本:4.5.0

尝试不使用 count 功能,也尝试使用 for_each 功能

resource "aws_s3_bucket" "public_bucket" {
  count = "${length(var.public_bucket_names)}"
  bucket = "${var.public_bucket_names[count.index]}"
  # acceleration_status = var.public_bucket_acceleration

  tags = {
    ProjectName        = "${var.project_name}"
    Environment        = "${var.env_suffix}"
  }
}


resource "aws_s3_bucket_versioning" "public_bucket_versioning" {

  bucket = aws_s3_bucket.public_bucket[count.index].id 

  versioning_configuration {
    status =   "Enabled"
  }
}

面临以下错误

 Error: Reference to "count" in non-counted context
│ 
│   on modules/S3-Public/s3-public.tf line 24, in resource "aws_s3_bucket_versioning" "public_bucket_versioning":
│   24:   bucket = aws_s3_bucket.public_bucket[count.index].id 
│ 
│ The "count" object can only be used in "module", "resource", and "data" blocks, and only when the "count" argument is set.

您当前的代码创建了多个 S3 存储桶,但仅尝试创建单个存储桶版本控制配置。您正在引用存储桶版本控制资源中的 count 变量,但您尚未为该资源声明​​ count 属性。

您需要在存储桶版本控制资源上声明count,就像您对 s3 存储桶资源所做的那样。

resource "aws_s3_bucket_versioning" "public_bucket_versioning" {
  count = "${length(var.public_bucket_names)}"
  bucket = aws_s3_bucket.public_bucket[count.index].id 

  versioning_configuration {
    status =   "Enabled"
  }
}