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

Time:03-19

Trying to create multiple AWS s3 buckets using Terraform with the below-provided code. Provider Version: 4.5.0

Tried without count function and with for_each function as well

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"
  }
}

Facing below error

 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.

CodePudding user response:

Your current code creates multiple S3 buckets, but only attempts to create a single bucket versioning configuration. You are referencing a count variable inside the bucket versioning resource, but you haven't declared a count attribute for that resource yet.

You need to declare count on the bucket versioning resource, just like you did for the s3 bucket resource.

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"
  }
}
  • Related