简体   繁体   中英

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?

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:

桶图像

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM