Conditional serverless.yml based on stage?

This was helpful, as I was looking for this kind of thing as well. I’d agree that for a lot of uses, the solution of having settings for each stage in the custom section is the way to go. But, I needed to conditional a ton of stuff in the resources section. I just wanted to add a small bit to what @ezeeetm’s example provides.

When you create the named condition in the Conditions section of resources, you then need to specify that named condition for each resource you want to condition. Here’s an example:

resources:
  Conditions:
    # Only create the VPC setup in the dev account/stage
    CreateVPCResources:
      Fn::Equals:
        - ${self:provider.stage}
        - dev
  Resources:
    MyVPC:
      Type: AWS::EC2::VPC
      Condition: CreateVPCResources
      Properties:
        CidrBlock: 10.0.0.0/16

Any resources in there that don’t specify that Condition: ... attribute will of course not be affected. More info can be found in the CloudFormation docs for Conditions.

1 Like