🐶
Terraform

Terraform AWS Lambda VPC Deployment Guide

By Ondřej Dolanský on 01/05/2025

Learn how to seamlessly integrate your AWS Lambda functions with your Amazon VPC networks using Terraform for secure and controlled access to resources.

Terraform AWS Lambda VPC Deployment Guide

Table of Contents

Introduction

This guide provides a step-by-step approach to deploying AWS Lambda functions within a Virtual Private Cloud (VPC) using Terraform. We'll cover VPC resource creation, Lambda function configuration, necessary permissions, and deployment. Additionally, we'll highlight important considerations for running Lambda functions in a VPC environment.

Step-by-Step Guide

  1. Define VPC resources: If you don't have an existing VPC, create one along with subnets and security groups.
resource "aws_vpc" "example" {
  cidr_block = "10.0.0.0/16"
}

resource "aws_subnet" "example" {
  vpc_id     = aws_vpc.example.id
  cidr_block = "10.0.1.0/24"
}

resource "aws_security_group" "example" {
  name = "example"
  vpc_id = aws_vpc.example.id
}
  1. Configure Lambda function with VPC settings: In your aws_lambda_function resource, specify the VPC configuration.
resource "aws_lambda_function" "example" {
  # ... other configurations ...

  vpc_config {
    subnet_ids         = [aws_subnet.example.id]
    security_group_ids = [aws_security_group.example.id]
  }
}
  1. Ensure necessary permissions: Your Lambda function's IAM role needs permissions to access resources within the VPC.
resource "aws_iam_role_policy_attachment" "example" {
  role       = aws_iam_role.example.name
  policy_arn = "arn:aws:iam::aws:policy/service-role/AWSLambdaVPCAccessExecutionRole"
}
  1. Deploy and test: Apply your Terraform configuration and test your Lambda function to ensure it can access resources within the VPC.

Important Considerations:

  • Deletion: Deleting Lambda functions associated with a VPC can take longer due to ENI cleanup.
  • Networking: Understand the implications of placing your Lambda function within your VPC, such as network connectivity and security.
  • Performance: VPC networking can introduce latency to your Lambda function's execution time.
  • Resource Limits: Be aware of VPC resource limits, such as the number of ENIs per subnet.

Code Example

This Terraform code defines infrastructure for deploying a Lambda function within a VPC. It sets up a VPC with a subnet and security group, creates an IAM role with necessary permissions for the Lambda function to access VPC resources, and finally defines the Lambda function itself, configuring it to use the defined VPC, subnet, and security group. Replace placeholders for filename, source code hash, and handler with your actual Lambda function code. Adjust security group rules as needed.

This example demonstrates how to create a Lambda function within a VPC and configure it to access resources within that VPC.

# Configure the AWS Provider
terraform {
  required_providers {
    aws = {
      source  = "hashicorp/aws"
      version = "~> 4.0"
    }
  }
}

# Configure variables (optional)
variable "vpc_cidr" {
  default = "10.0.0.0/16"
}

variable "subnet_cidr" {
  default = "10.0.1.0/24"
}

# Create a VPC
resource "aws_vpc" "example" {
  cidr_block = var.vpc_cidr
}

# Create a subnet
resource "aws_subnet" "example" {
  vpc_id     = aws_vpc.example.id
  cidr_block = var.subnet_cidr
}

# Create a security group
resource "aws_security_group" "example" {
  name   = "lambda-sg"
  vpc_id = aws_vpc.example.id

  ingress {
    from_port   = 443
    to_port     = 443
    protocol    = "tcp"
    cidr_blocks = ["0.0.0.0/0"]
  }

  egress {
    from_port   = 0
    to_port     = 0
    protocol    = "-1"
    cidr_blocks = ["0.0.0.0/0"]
  }
}

# Create an IAM role for the Lambda function
resource "aws_iam_role" "example" {
  name = "lambda_role"

  assume_role_policy = <<POLICY
{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Action": "sts:AssumeRole",
      "Principal": {
        "Service": "lambda.amazonaws.com"
      },
      "Effect": "Allow",
      "Sid": ""
    }
  ]
}
POLICY
}

# Attach the AWSLambdaVPCAccessExecutionRole policy to the IAM role
resource "aws_iam_role_policy_attachment" "example" {
  role       = aws_iam_role.example.name
  policy_arn = "arn:aws:iam::aws:policy/service-role/AWSLambdaVPCAccessExecutionRole"
}

# Create a Lambda function
resource "aws_lambda_function" "example" {
  function_name = "example_function"
  runtime = "nodejs14.x"
  handler = "index.handler"
  role = aws_iam_role.example.arn

  # Replace with your actual Lambda function code
  filename         = "lambda_function.zip"
  source_code_hash = filebase64sha256("lambda_function.zip")

  # Configure VPC settings
  vpc_config {
    subnet_ids         = [aws_subnet.example.id]
    security_group_ids = [aws_security_group.example.id]
  }
}

Explanation:

  1. VPC, Subnet, and Security Group: The code creates a VPC, a subnet within that VPC, and a security group. The security group allows inbound traffic on port 443 and outbound traffic on all ports.
  2. IAM Role: An IAM role is created for the Lambda function and the AWSLambdaVPCAccessExecutionRole policy is attached to it. This policy allows the Lambda function to access resources within the VPC.
  3. Lambda Function: The code defines a Lambda function with the necessary configurations, including the runtime, handler, and IAM role.
  4. VPC Configuration: The vpc_config block within the aws_lambda_function resource specifies the subnet and security group to associate with the Lambda function. This enables the function to be launched within the VPC and access resources within it.

Remember to:

  • Replace the placeholder values for filename, source_code_hash, and handler with your actual Lambda function code and configuration.
  • Adjust the security group rules to allow the necessary traffic for your specific use case.
  • Consider the important considerations mentioned in the article, such as deletion time, networking implications, performance, and resource limits.

This example provides a basic framework for deploying a Lambda function within a VPC. You can customize it further based on your specific requirements and use case.

Additional Notes

  • VPC Design: Carefully plan your VPC subnets and security groups before deploying Lambda functions. Consider factors like routing, availability, and security requirements.
  • Internet Access: Lambda functions within a VPC don't have direct internet access. To enable internet access, you'll need to configure a NAT Gateway or VPC Endpoint for S3 (if your function needs to access S3).
  • Security Best Practices: Follow security best practices when configuring security groups for your Lambda functions. Limit inbound and outbound traffic to only what's necessary.
  • Cold Starts: Placing Lambda functions within a VPC can increase cold start times due to the additional networking setup required. Consider using provisioned concurrency to mitigate cold starts if necessary.
  • Monitoring and Troubleshooting: Monitor your Lambda function's performance and logs closely after deploying it within a VPC. Network-related issues can sometimes arise, so be prepared to troubleshoot them.
  • Alternative Approaches: For simple use cases that don't require access to private resources within a VPC, consider using Lambda functions without VPC configuration for easier management and potentially better performance.
  • Terraform Modules: Consider using Terraform modules to simplify the deployment and management of your Lambda functions and VPC infrastructure. Modules can help you encapsulate reusable configurations and improve code organization.
  • State Management: Use a remote backend for Terraform state to enable collaboration and prevent accidental state loss. This is especially important for infrastructure deployments involving multiple team members.
  • Cost Optimization: Be mindful of the costs associated with running Lambda functions within a VPC, such as VPC resources and data transfer charges. Optimize your function's execution time and resource utilization to minimize costs.
  • Keep Updated: AWS Lambda and VPC networking features are constantly evolving. Stay up-to-date with the latest best practices and service updates to ensure optimal performance and security.

Summary

This guide outlines the process of connecting an AWS Lambda function to a Virtual Private Cloud (VPC) using Terraform.

Steps:

  1. VPC Setup: Define your VPC resources, including the VPC itself, subnets, and security groups.
  2. Lambda Configuration: Configure your Lambda function to use the VPC resources by specifying the subnet IDs and security group IDs within the vpc_config block.
  3. IAM Permissions: Grant your Lambda function's IAM role the necessary permissions to access resources within the VPC by attaching the AWSLambdaVPCAccessExecutionRole policy.
  4. Deployment and Testing: Deploy your Terraform configuration and test your Lambda function to ensure it can successfully access resources within the VPC.

Key Considerations:

  • Deletion Time: Deleting Lambda functions connected to a VPC may take longer due to Elastic Network Interface (ENI) cleanup.
  • Networking: Carefully consider the networking implications of placing your Lambda function within your VPC, including connectivity and security.
  • Performance: VPC networking can introduce latency to your Lambda function's execution time.
  • Resource Limits: Be mindful of VPC resource limits, such as the number of ENIs allowed per subnet.

Conclusion

By following these steps and considering the important factors outlined, you can successfully deploy and manage AWS Lambda functions within your VPCs, leveraging the benefits of both services for your serverless applications. Remember to adapt the provided code examples and configurations to your specific use case and security requirements. For further exploration, refer to the linked resources and AWS documentation to deepen your understanding of Lambda and VPC networking.

References

Were You Able to Follow the Instructions?

😍Love it!
😊Yes
😐Meh-gical
😞No
🤮Clickbait