Functions in serverless.yml optional?

Is there a way (or could there be a way) to make the creation of functions in the serverless.yml optional depending on something like your stage or another passed variable?

I’m hitting the 200 resource limit and as alternative to breaking up things into multiple projects, it dawned on me that a simpler way would be that the functions could simply have boolean similar to AWS’s “ShouldCreateResource” boolean that the function should be created or ignored.

This way, you could perhaps have two stages, i.e. prod-ui and prod-admin (for front end and back end calls) and then have some of your functions deploy for each of these two stages, yet all contained within one project (helpful when they may share model files or some other scenario that makes physically breaking apart the project more difficult).

You’d still wind up with all your node_modules dependencies as part of the zip no matter what, that’s a different issue, but for many use cases this may be acceptable or not matter.

Actually to answer my own question, I figured out a clever way to do this with existing functionality in the custom block.

The first step is that your functions should be already separated into subfiles and referenced from the primary serverless.yml, so before I had a block that looked like this:


    functions:
      adminUsersGet: ${file(serverless-admin.yml):adminUsersGet}
      adminUsersPost: ${file(serverless-admin.yml):adminUsersPost}
  
      publicUserLookup: ${file(serverless-public.yml):publicUserLookup}
      publicProcessCreditCard: ${file(serverless-public.yml):publicProcessCreditCard}

So I just moved this up to the custom block, like:

custom:
  functions:
    admin-prod:
      adminUsersGet: ${file(serverless-admin.yml):adminUsersGet}
      adminUsersPost: ${file(serverless-admin.yml):adminUsersPost}
    public-prod:
      publicUserLookup: ${file(serverless-public.yml):publicUserLookup}
      publicProcessCreditCard: ${file(serverless-public.yml):publicProcessCreditCard}

And then just changed the functions to respect the stage:

    functions: ${self:custom.functions.${opt:stage, self:provider.stage}}

And now a different group of functions are deployed based on stage, and I can have admin-dev and admin-prod etc just all defined in custom:

1 Like