如何通过Serverless Framework将Lambda部署至现有VPC安全组?
Absolutely! You can deploy a Lambda function via Serverless Framework that connects to an existing VPC's security groups—without your deployment stack owning any network resources. Here's a practical, step-by-step breakdown to make it happen:
Core Idea
The trick is to reference existing VPC resources directly in your Serverless config, instead of defining new network resources (like security groups or subnets) within your CloudFormation stack. This way, your stack only associates Lambda with pre-existing assets, not creates or owns them.
Step-by-Step Implementation
1. Gather Existing VPC Resource IDs
First, get the IDs of your target security groups and subnets. You can fetch these via:
- AWS Console (navigate to VPC dashboard > Security Groups/Subnets)
- AWS CLI commands:
# List security groups in your VPC aws ec2 describe-security-groups --filters "Name=vpc-id,Values=your-vpc-id" # List subnets in your VPC aws ec2 describe-subnets --filters "Name=vpc-id,Values=your-vpc-id"
2. Update Your Serverless.yml Configuration
Add a vpc block to your Lambda function (or globally for all functions) and plug in the existing resource IDs. Here's a sample configuration:
service: my-vpc-connected-lambda provider: name: aws runtime: nodejs18.x region: us-west-2 functions: secureBackendFunction: handler: src/handler.main vpc: securityGroupIds: - sg-0a1b2c3d4e5f6g7h8 # Replace with your existing security group ID subnetIds: - subnet-0123456789abcdef0 # Replace with your existing subnet ID - subnet-0fedcba9876543210 # Add multiple subnets for high availability
3. Key Considerations
- No Network Resource Ownership: Since you’re using direct ID references instead of CloudFormation resource definitions (like
AWS::EC2::SecurityGroup), your Serverless stack won’t manage these VPC assets—they stay under their original ownership. - Lambda VPC Access Needs: Ensure your chosen subnets have access to any AWS services your Lambda requires (e.g., S3, DynamoDB). If not, use existing VPC endpoints or NAT gateways (don’t create new ones in your stack).
- IAM Permissions: Your deployment IAM role needs permissions to associate Lambda with VPC resources. The default Serverless IAM policy includes this, but double-check if you’ve customized your role.
Verify the Setup
After deployment:
- Head to the AWS Lambda console, select your function, and check the "VPC" tab—you’ll see your existing security groups and subnets listed.
- Run a test invocation to confirm the Lambda can communicate with resources in the VPC as expected.
内容的提问来源于stack exchange,提问作者Ryan Fisch




