amazon-web-servicesamazon-s3terraform-provider-aws

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


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?


Solution

  • Another solution by using bucket instead of bucket_prefix and random_uuid, for example:

    resource "aws_s3_bucket" "my_s3_bucket" {
      bucket = "my-s3-bucket-${random_uuid.uuid.result}"
    }
    
    resource "random_uuid" "uuid" {}
    

    This will give you a name like this:

    my-s3-bucket-ebb92011-3cd9-503f-0977-7371102405f5