简体   繁体   中英

How to import existing S3 bucket from another stack in CloudFormation?

I'd like to import an existing S3 bucket that is created in another stack. I tried to do it using two CF templates below but when I try to create a consumer stack it leads to a CREATE_FAILED event with an "already exists" error message.

Producer template:

"AWSTemplateFormatVersion": "2010-09-09",
"Description": "Main stack that creates S3 bucket.",
"Resources": {
"myS3Bucket" : {
      "Type" : "AWS::S3::Bucket",
      "DeletionPolicy" : "Retain",
      "Properties": {"BucketName": "bucket-name" }
    }
},
"Outputs": {
    "BucketId": {
        "Description": "Bucket ID",
        "Value": { "Ref": "myS3Bucket" },
        "Export": { "Name": { "Fn::Sub": "${AWS::StackName}-BUCKETID" }}
        }
    }
} 

And this is a consumer stack template:

{
    "AWSTemplateFormatVersion": "2010-09-09",
    "Description": "AWS CloudFormation Sample Template.",
    "Resources" : { 
        "S3ImportedBucket" : {  
            "Type" : "AWS::S3::Bucket",
            "Properties" : {
                "BucketName" : { "Fn::ImportValue" : "main-BUCKETID"} 
            }
        }
    }
}

What should be changed in the templates to make it work?

tl;dr : the concept of outputs is right but you are using it in a wrong way

explanation In cloudformation templates, you are posting

Both create a resource of s3 bucket type with the same name so whatever runs first will create the s3 bucket

you can check here for reference

however, the output can be used as a reference in other templates like if you are uploading something from lambda so you can set that bucket as env var and use it inside the lambda (just an example)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM