Cybex
Cybex

Reputation: 551

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?

Upvotes: 1

Views: 1538

Answers (1)

Kerolos William
Kerolos William

Reputation: 481

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)

Upvotes: 2

Related Questions