How to ensure an S3 bucket name is not used with Terraform?

Viewed 1775

I know the data aws_s3_bucket resource can be used to get a reference to an existing bucket, but how would it be used to ensure that a new potential bucket name is unique?

I'm thinking a loop using random numbers, but how can that be used to search for a bucket name which has not been used?

1 Answers

As discussed in the comments, this behaviour can be achieved with the bucket_prefix functionality

This code:

resource "aws_s3_bucket" "my_s3_bucket" {
  bucket_prefix = "my-stackoverflow-bucket-"
  acl    = "private"

  tags = {
    Name        = "My bucket"
    Environment = "Dev"
  }
}

Produces the following unique bucket:

bucket image

Related