Skip to content

Instantly share code, notes, and snippets.

@decagondev
Created November 19, 2024 14:33
Show Gist options
  • Save decagondev/11d7cc64bfcdda2660dbe70b98aaf0a3 to your computer and use it in GitHub Desktop.
Save decagondev/11d7cc64bfcdda2660dbe70b98aaf0a3 to your computer and use it in GitHub Desktop.

Steps to Connect AWS Lambda to a Private VPC

  1. Identify the VPC and Subnets:

    • Determine the private VPC ID where your resources reside.
    • Identify at least two subnets within the VPC for high availability (preferably in different availability zones).
  2. Configure Security Groups:

    • Create or use an existing security group that allows the Lambda function to connect to the necessary resources in the private VPC.
      • Allow the Lambda function's security group to access the resources' ports (e.g., database ports).
      • Ensure outbound traffic from the Lambda function is allowed for required services.
  3. Configure the Lambda Function:

    • In the AWS Management Console, navigate to your Lambda function.
    • Go to the Configuration tab and select VPC under the Network settings section.
    • Choose the private VPC and subnets where the Lambda function will reside.
    • Assign the security group created or identified in step 2.
  4. Add an Internet Gateway or NAT Gateway (if required):

    • If the Lambda function needs to connect to the internet (e.g., for accessing external APIs), you must configure:
      • A NAT Gateway in the public subnet of your VPC with appropriate route table configurations.
      • Alternatively, an Internet Gateway (if no NAT Gateway is available, but this is less common for private VPC setups).
  5. Test the Setup:

    • Deploy and test your Lambda function to ensure it can access the resources within the VPC.
  6. IAM Role Permissions:

    • Ensure the Lambda execution role has the necessary permissions to access the VPC. This typically includes:
      • ec2:CreateNetworkInterface
      • ec2:DescribeNetworkInterfaces
      • ec2:DeleteNetworkInterface

Example IAM policy for the Lambda execution role:

{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Effect": "Allow",
      "Action": [
        "ec2:CreateNetworkInterface",
        "ec2:DescribeNetworkInterfaces",
        "ec2:DeleteNetworkInterface"
      ],
      "Resource": "*"
    }
  ]
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment