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

穿精又带淫゛_ 提交于 2019-12-24 17:04:34

问题


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 ?


回答1:


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" }]]}}
    ]
  }
}



回答2:


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"
      }
    }
  }
}


来源:https://stackoverflow.com/questions/25680599/amazon-web-services-tag-a-s3-bucket-with-its-own-name-within-a-cloudformation

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!