DEV Community

joahna
joahna

Posted on

Create a Unique S3 Bucket Name Using CloudFormation

An Amazon S3 bucket name is globally unique, and the namespace is shared by all AWS accounts. This means that once you create an S3 bucket named “my-test-bucket”, you or anyone else cannot create a bucket with the same name even in any other AWS regions or accounts until you delete that bucket.

This is particularly challenging when you are creating S3 buckets using CloudFormation and you want to reuse the template multiple times (e.g. when you are deploying your application in different AWS accounts).

To help with bucket naming, here is a template to create an S3 bucket with a unique name using CloudFormation:

Parameters:
  BucketPrefix:
    Description: Value that will be prefixed to the bucket name

Resources:
  S3Bucket:
    Type: AWS::S3::Bucket
    Properties:
      BucketName: !Join 
        - '-'
        - - !Ref BucketPrefix
          - !Ref AWS::AccountId
          - !Ref AWS::Region
          - 'bucket'
          - !Select 
            - 0
            - !Split 
              - '-'
              - !Select 
                - 2
                - !Split 
                  - /
                  - !Ref AWS::StackId

Enter fullscreen mode Exit fullscreen mode

In this template, we used CloudFormation pseudo parameters AWS::AccountId, AWS::Region and AWS::StackId to create a unique bucket name.

The AWS::StackId helps give your bucket a random name. The CloudFormation intrinsic functions Select and Split were used to select the last range of the CloudFormation Stack ID.

Discussion (0)