Search code examples
amazon-web-servicesaws-lambdaserverless-framework

How can I use conditional configuration in serverless.yml for lambda?


I need to configure a lambda via serverless.yml to use different provision concurrency for different environments. Below is my lambda configuration:

 myLambda:
   handler: src/lambdas
   name: myLambda
   provisionedConcurrency: ${self:custom.pc}

...

custom:
  pc: ${env:PC}

The value PC is loaded from environment variable. It works for values greater than 0 but I can't set a value 0 in one environment. What I want to do is to disable provision concurrency in dev environment.

I have read through this doc https://forum.serverless.com/t/conditional-serverless-yml-based-on-stage/1763/3 but it doesn't seem to help in my case.

How can I set provisionedConcurrency conditional based on environment?


Solution

  • For really sticky problems, I find it's useful to go to the Cloudformation script instead and use the Cloudformation Intrinsic Functions.

    For this case, if you know all the environments you could use Fn::FindInMap

    https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/intrinsic-function-reference-findinmap.html

    Or if it's JUST production which needs 0 then you could use the conditional Fn::If and a boolean Condition test in the Cloudformation template to test if environment equals production, use 0, else use the templated value from SLS.

    Potential SLS:

    resources:
      Conditions:
        UseZero: !Equals ["production", ${provider.stage}]
      Resources:
        myLambda:
          ProvisionedConcurrency: !If [UseZero, 0, ${self:custom.pc}]
    

    You can explicitly remove the ProvisionedConcurrency property as well if you want:

    resources:
      Conditions:
        UseZero: !Equals ["production", ${provider.stage}]
      Resources:
        myLambda:
          ProvisionedConcurrency: !If [UseZero, AWS::NoValue, ${self:custom.pc}]
    

    Edit: You can still use SLS to deploy; it simply compiles into a Cloudformation JSON template which you can explicitly modify with the SLS resources field.