Matt W
Matt W

Reputation: 12423

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?

Upvotes: 7

Views: 5624

Answers (2)

Youcef LAIDANI
Youcef LAIDANI

Reputation: 59978

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

Upvotes: 3

Jaime S
Jaime S

Reputation: 1698

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

Upvotes: 16

Related Questions