Search code examples
serverlessserverless-framework

How to declare conditional resource in serverless framework


I use typescript definition of serverless configuration (serverless.ts). How do I conditionally add resources using cloud formation templates ? For example AWS cognito userpools, if I want to exclude these for offline mode, how can I specify it in serverless config file to not include them?


Solution

  • I solved it 2 ways. serverless-plugin-ifelse allowed me to exclude resources based on certain parameters.

    Later I realized this may be problematic in the long run. So I created separate serverless config file for my offline use case to include all necessary resources. Prod/Staging environments used default serverless.ts file. Offline uses offline-serverless.ts file. Though there is some repetition of the resources config, this option ensures prod/staging config is not polluted with offline content. I could start offline using sls offline start --stage local --reloadHandler --config offline-serverless.ts

    And the offline config reuses some code from main config. Sample offline-serverless.ts content is below:

        import offlineplugins from "offlineplugins";
        import pluginsconfig from "offlinepluginsconfig";
        import plugins from "plugins";
        
        const serverlessConfiguration: AWS = {
          service: "my-offline-apis",
          frameworkVersion: "3",
          ...pluginsconfig,
          plugins: [...plugins, ...offlineplugins],
          provider: {
            name: "aws",
       ....
       ....