Search code examples
amazon-web-servicesamazon-s3aws-lambdaserverlessserverless-framework

Serverless framework tries to create a new S3 bucket instead of refercing an existing one


Here's my AWS S3 bucket inside serverless.yml file

    serverlessKinesisFirehoseBucket:
      Type: AWS::S3::Bucket
      DeletionPolicy: Retain
      Properties:
        BucketName: "${self:service}-${self:provider.stage}"
        LifecycleConfiguration:
          Rules:
            - Status: Enabled
              ExpirationInDays: 90

When I run

serverless deploy --stage dev --region eu-central-1

It fails with the error message:

Error:
CREATE_FAILED: serverlessKinesisFirehoseBucket (AWS::S3::Bucket)
sensor-processor-v3-dev already exists

That's because all S3 bucket names should be unique across all AWS regions.


I found out that I need to reference an S3 bucket instead of creating one. How can I do that?


Solution

  • I think you can use Outputs and export the S3 bucket name from old Cloudformation template and import it to other templates like below:

    Outputs:
      TheCreatedS3BucketName:
        Description: Name of the old S3 bucket.
        Value: !Ref <Resource Name>
        Export:
          Name: sensor-processor-v3-dev
    

    Import it to other templates:

    serverlessKinesisFirehoseBucket:
      Type: AWS::S3::Bucket
      DeletionPolicy: Retain
      Properties:
        BucketName: Fn::ImportValue 
            'Fn::Sub': 'sensor-processor-v3-dev'
        LifecycleConfiguration:
        ...
    

    Another solution is using random/stack-id in S3 bucket name. You will have many S3 buckets.