Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set semi-random name for S3 bucket using cloud formation

I want to create a cloud formation template that creates an S3 bucket with a human readable name, but which can be run many times automatically. Below is a bucket with predefined name.

What can I do to make the name contain a human readable portion in addition to a random unique id? Something like: MyBucket-abcdabcd, MyBucket-efghefgh, MyBucket-ijklijkl.

"S3Bucket" : {
  "Type" : "AWS::S3::Bucket",
  "Properties" : {
    "BucketName": "MyBucket",
    "PublicAccessBlockConfiguration" : {
      "BlockPublicAcls" : true,
      "BlockPublicPolicy" : true
    }
  }
}
like image 794
Yason Avatar asked Feb 27 '19 03:02

Yason


People also ask

How do you get a bucket name in CloudFormation?

Use the function Get Attribute above to get the s3 bucket name that cloudformation created. Insert the value into a file, you can use the UserData , or use Metadata if you are using cloud-init already.

How do you name resources in CloudFormation?

Names must begin with a letter; contain only ASCII letters, digits, and hyphens; and not end with a hyphen or contain two consecutive hyphens. Also, don't manage stack resources outside of CloudFormation.

How set S3 bucket name?

The following rules apply for naming buckets in Amazon S3: Bucket names must be between 3 (min) and 63 (max) characters long. Bucket names can consist only of lowercase letters, numbers, dots (.), and hyphens (-). Bucket names must begin and end with a letter or number.

Can you alias an S3 bucket?

Aliases for S3 Access Points are automatically generated and are interchangeable with S3 bucket names anywhere you use a bucket name for data access. You can use an Access Point alias anywhere a bucket name is used today to perform object-level operations such as PUT, GET, LIST, and more.


1 Answers

You have two options.

First option - you can just leave your BucketName property blank. When you leave it blank, it'll yield a name of: <stackname>-<template logical name>-<random suffix>

So, if you have stack name and template logical name that make sense, it should give you a unique bucket name every time.

Second option - use the Stack ARN suffix, which is a random guid: arn:aws:cloudformation:us-west-2:123456789012:stack/teststack/51af3dc0-da77-11e4-872e-1234567db123

!Select [2, !Split [/, !Ref AWS::StackId ]]

That would yield you '51af3dc0-da77-11e4-872e-1234567db123' You can further split that again and select a portion if you want.

!Select [0, !Split[-, !Select [2, !Split [/, !Ref AWS::StackId ]]]]

Gives you 51af3dc0

like image 103
Sleeper Smith Avatar answered Sep 28 '22 06:09

Sleeper Smith