Generating a Uniquifier for Your Resources in CloudFormation

I don’t generally name CloudFormation resources explicitly. However, once in a while, I want to explicitly name a resource, and I want whatever this resource name is to be unique across stacks. This lets me deploy multiple instances of the stack without worrying about naming collision. Oh, and I don’t want the unique portion of the name to change each time I update the stack. This is important. If I use this technique on an S3 bucket (for example), I’d get a new bucket with each stack update, and I don’t want that.

One quick-and-dirty way to accomplish this is to leverage the stack id(entifier). Consider the CloudFormation template:

---
Outputs:
  MyBucket:
    Value: !Select [6, !Split [ "-", !Ref "AWS::StackId" ]]
    Export:
      Name: "MyBucket"
Resources:
  MyBucket:
    Type: "AWS::S3::Bucket"
    Properties:
      BucketName: !Sub
        - "mybucket-${Uniquifier}"
        - Uniquifier: !Select [6, !Split [ "-", !Ref "AWS::StackId" ]]

I’m building the template with something like the following (run in bash):

aws cloudformation deploy \
--stack-name "KewlStackAdamGaveMe" \
--template-file "<full-path-to-template-file>" \
--capabilities CAPABILITY_IAM

You’ll end up with a stack and S3 bucket that looks like the following:

Deployed Cloudformation Stack

I’m using the last the last 12-characters of the stack id, but you can use the whole thing if you’d like to. Keep in mind the naming rules for S3 buckets. Either way, you get the gist of how I’m creating a unique name that stays unique across stack updates.