Amazon Web Services - Tag a S3 bucket with its own name within a CloudFormation

I am currently fighting with AWS CloudFormation because I want to tag a bucket with its own name (in order to separate its costs in my Cost Allocation report).

When I do

"MyBucket" : {
        "Type" : "AWS::S3::Bucket",
            "Properties" : {
                "AccessControl" : "Private",
                "Tags" : [
                    { "Key" : "Name", "Value" : { "Ref" : "MyBucket" } }
                ]
        }
    },  

the CloudFormation wizard throws the following error:

Error
Template validation error: Circular dependency between resources: [MyBucket]

The real problem is that I want to keep the generated name (such as my-bucket-15jsi17g9cby0) as not specify a custom name through the "BucketName" property.

Does anybody have an idea ?

Upvotes: 1

Views: 3332

Answers (2)

Sriwantha Attanayake
Sriwantha Attanayake

Reputation: 7908

You can use stack id parameter and join it to form a unique id. E.g.

{
  "AWSTemplateFormatVersion": "2010-09-09",
  "Resources": {
    "MyBucket": {
      "Type": "AWS::S3::Bucket",
      "Properties": {
        "BucketName": {
            "Fn::Join": [
            "-",
            [
              "my-bucket-name",
              {
                "Fn::Select": [
                  "2",
                  {
                    "Fn::Split": [
                      "/",
                      { "Ref": "AWS::StackId" }
                    ]
                  }
                ]
              }
            ]
          ]
        },
        "AccessControl": "Private"
      }
    }
  }
}

Upvotes: 0

Jason
Jason

Reputation: 2105

You could use the CloudFormation pseudo parameters to generate a unique name for the BucketName and the Name tag value. This is similar to what the template generates automatically. This also guarantees a unique name since the stack name combined with the region must be unique to CloudFormation. If you're only using a single region, you could drop the region reference.

"MyBucket" : {
  "Type" : "AWS::S3::Bucket",
  "Properties" : {
    "BucketName" : { "Fn::Join" : [ "-", [{ "Ref" : "AWS::StackName" }, "s3", { "Ref" : "AWS::Region" }]]},
    "AccessControl" : "Private",
    "Tags" : [
      { "Key" : "Name", "Value" : { "Fn::Join" : [ "-", [{ "Ref" : "AWS::StackName" }, "s3", { "Ref" : "AWS::Region" }]]}}
    ]
  }
}

Upvotes: 1

Related Questions