CodexBloom - Programming Q&A Platform

Terraform: how to to Deploy Multiple S3 Buckets with Unique Names Using Dynamic Naming Convention

πŸ‘€ Views: 186 πŸ’¬ Answers: 1 πŸ“… Created: 2025-06-11
terraform aws s3 infrastructure-as-code HCL

I've hit a wall trying to I'm working on a personal project and I'm currently trying to deploy multiple S3 buckets with unique names based on a dynamic naming convention but I'm running into issues with the bucket name uniqueness requirement. I have the following configuration: ```hcl variable "bucket_count" { default = 3 } resource "aws_s3_bucket" "unique_buckets" { for_each = toset([for i in range(var.bucket_count) : format("my-unique-bucket-%d", i)]) bucket = each.key acl = "private" } ``` When I run `terraform apply`, I receive the following behavior message: ``` behavior: BucketAlreadyExists: The specified bucket already exists status code: 409, request id: XXX, host id: YYY ``` I tried changing the naming format to include a timestamp and even appended a random string generator but I still get the same behavior. Here’s the modified code I attempted using the `random_string` resource: ```hcl resource "random_string" "bucket_suffix" { length = 8 special = false } resource "aws_s3_bucket" "unique_buckets" { for_each = toset([for i in range(var.bucket_count) : format("my-unique-bucket-%d-%s", i, random_string.bucket_suffix.result)]) bucket = each.key acl = "private" } ``` However, this still does not solve the question because the `random_string` resource generates a new value on every plan/apply cycle which results in the bucket names changing each time, making it impossible to manage them. I’m looking for advice on how to effectively generate unique bucket names while ensuring that they continue across runs without working with the `BucketAlreadyExists` behavior. Any suggestions on best practices for naming conventions in this scenario would be greatly appreciated! My development environment is Ubuntu. Any ideas what could be causing this? I've been using Hcl for about a year now.