coyoteecd / serverless-s3-cleaner

Serverless Framework plugin that empties S3 buckets before removing a stack
MIT License
16 stars 4 forks source link

Reference a randomly named bucket? #4

Open cnuss opened 6 months ago

cnuss commented 6 months ago

I have a S3 bucket in serverless.yaml resources:

resources:
  Resources:
    Bucket:
      Type: AWS::S3::Bucket
      Properties:
        BucketEncryption:
          ServerSideEncryptionConfiguration:
            - ServerSideEncryptionByDefault:
                SSEAlgorithm: 'AES256'

Note: I've left off the BucketName property, so I get a random-ish bucket name.

In serverless.yaml its possible to use the Ref syntax for dynamic injection of the bucket name, for example with environment:

provider:
  name: aws
  # ...SNIP...
  environment:
    BUCKET_NAME: { Ref: Bucket }

Is there a method to "inject" the randomized bucket name from CloudFormation State? Ideally I'd like to do something like:

plugins:
  - serverless-s3-cleaner

custom:
  serverless-s3-cleaner:
    prompt: false
    buckets:
      - { Ref: Bucket } # or something similar to get the bucket name
coyoteecd commented 6 months ago

@cnuss that won't work for the reasons explained here. The plugin must run before (re)deploying a stack, since its main purpose is exactly to clear out the bucket before the stack deployment runs, otherwise it fails.

This means that embedding a !Ref does not work; this only works for plugins that modify the stack template.

The closest you would get is that cf:stackName example that I've shown in the referenced comment. At the time of posting it, that did not work because Serverless Framework was attempting to resolve the variables and would fail because (obviously) the stack is not yet deployed when first running a deploy. I haven't tried it since, maybe you could try to get it to fall back to a default value when the stack does not exist...?