Serverless Framework add Lambda to an Existing VPC and Subnet
An extension to the answer provided by @Nebulastic.
This is when you want to configure your VPC Lambda's to execute from more than one subnet for various Stages.
provider:
name: aws
vpc:
securityGroupIds:
- ${self:custom.securityGroupId.${self:provider.stage}}
subnetIds:
- ${self:custom.subnetId1.${self:provider.stage}}
- ${self:custom.subnetId2.${self:provider.stage}}
- ${self:custom.subnetId3.${self:provider.stage}}
custom:
stage: ${opt:stage, self:provider.stage}
securityGroupId:
prod: sgId-prod
test: sgId-test
dev: sgId-dev
subnetId1:
prod: subnetId1-prod
test: subnetId1-test
dev: subnetId1-dev
subnetId2:
prod: subnetId2-prod
test: subnetId2-test
dev: subnetId2-dev
subnetId2:
prod: subnetId3-prod
test: subnetId3-test
dev: subnetId3-dev
Yes it is. The vpc
configuration in serverless.yml
just needs to reference existing subnets and security groups. Something like this:
vpc:
securityGroupIds:
- securityGroupId1
- securityGroupId2
subnetIds:
- subnetId1
- subnetId2
Take a look at https://serverless.com/framework/docs/providers/aws/guide/functions/#vpc-configuration
The following setup worked perfectly for me in Serverless version 1.51.0. I included staging variables, since my environments use different subnets and security groups for logical isolation. My network setup is an already existing VPC with subnets and security groups.
provider:
name: aws
....
....
vpc:
securityGroupIds:
- ${self:custom.securityGroupId.${self:provider.stage}}
subnetIds:
- ${self:custom.subnetId.${self:provider.stage}}
custom:
stages:
- tst
- dev
- prd
securityGroupId:
local: sg-local
tst: sg-tst
dev: sg-dev
prd: sg-prd
subnetId:
local: subnet-local
tst: subnet-tst
dev: subnet-dev
prd: subnet-prd
plugins:
- serverless-stage-manager