Serverless add AWS lambda to an existing VPC¶
While developing the serverless applications we may need to access the resources which are in VPC. If we are using AWS Lambda functions then we need to add the lambda function to the VPC.
To get started with AWS VPC visit the link https://docs.aws.amazon.com/vpc/latest/userguide/what-is-amazon-vpc.html. Follow the instructions to create the VPC and it's components.
How to add lambda function to AWS VPC in serverless¶
- we can add lambda function to VPC by adding a
vpc
object property inserverless.yaml
file. - Let's see an example configurations below.
VPC configuration to a specific function¶
# serverless.yml
service: service-name
provider: aws
functions:
hello:
handler: handler.hello
vpc:
securityGroupIds:
- securityGroupId1
- securityGroupId2
subnetIds:
- subnetId1
- subnetId2
VPC configuration to all functions in the service¶
# serverless.yml
service: service-name
provider:
name: aws
vpc:
securityGroupIds:
- securityGroupId1
- securityGroupId2
subnetIds:
- subnetId1
- subnetId2
functions:
hello:
handler: handler.hello
users:
handler: handler.users
- If we want to override the VPC configuration for one of the functions then we can simple override the property
vpc
in that specific function.
IAM role permissions required for VPC access¶
- Lambda function requires following IAM role permissions
ec2:CreateNetworkInterface
ec2:DescribeNetworkInterfaces
ec2:DeleteNetworkInterface
- The final
serverless.yml
looks something like below.
# serverless.yml
service: service-name
provider: aws
functions:
hello:
handler: handler.hello
iamRoleStatements:
- Effect: "Allow"
Action:
- ec2:CreateNetworkInterface
- ec2:DescribeNetworkInterfaces
- ec2:DeleteNetworkInterface
Resource: "*"
vpc:
securityGroupIds:
- securityGroupId1
- securityGroupId2
subnetIds:
- subnetId1
- subnetId2
Note: It requires plugin serverless-iam-roles-per-function
References: