Is there a way to conditionally specify a VPC



I know that you can use stage/environment variables to specify different securityGroupIds/subnetIds for different stages (dev/test/prod) but I have a situation where the Lambda function must be in a VPC when in the dev/test environment (to access private test resources) but should not be in a VPC in production (no need to access the resources and being in the VPC slows down startup performance).

Is there a way to make the whole VPC section conditional based on the stage? I tried leaving the env vars empty or not setting them at all but I get deployment errors when I do that.

Is there any way to do this without having to maintain separate serverless.yml files for dev and prod?


No, there is not way to conditionally include/exclude parts of the serverless.yml, because it’s not a great idea to do so.

While I can totally understand your use-case, what you’re doing may come back to bite you (and often does in larger projects and environments); Since your dev/test environment does not represent your prod environment, it’s conceivable your application will works in dev/test, but have a bug in prod.

That being said (and I feel dirty suggesting this :smiley:), you could try to use CFN Conditionals to do what you’ve described. Remember that the resources section of your serverless.yml is merged with the final generated CFN template, so by adding in Conditions to your resources you might be able to do it (e.g. have two function definitions, one for dev/test that is VPC’d, and one for prod that is not).


Did you ever find a reasonable solution for this issue @talawahtech?


It might be possible using something like:

      dummyValue: "This is a dummy value that should be ignored"
          - securityGroupId1
          - securityGroupId2
          - subnetId1
          - subnetId2
  vpcSettings: &vpcSettings
    vpc: ${self:custom.allVpcSettings.${self.provider.stage}.vpc}

  <<: *vpcSettings
  # Rest of the provider config

# OR
    <<: *vpcSettings
    # Rest of the function config

It’s mixing stage specific variables with YAML anchors in an attempt to get vpcSettings to contain the right value.