DEV Community

Cover image for Internet access for lambda in VPC
Afraz Khan
Afraz Khan

Posted on • Edited on

Internet access for lambda in VPC

AWS resources living inside a VPC have some security layers attached; usually, such resources (Redis, DB, EC2 instances, etc.) are located inside private subnets. If your Lambda functions need to interact with these private resources, then you need to configure VPC access for your lambda functions, and below are the steps listed to do that:

How to attach VPC to your lambdas:

  1. Create 2 new private subnets specifically for your lambdas and label them in such a way so that they are distinguishable as private subnets.
  2. If delegated VPC has no Internet Gateway attached, create one and attach to VPC.
  3. Create a NAT Gateway and give it a public subnet. (create if not avail)
  4. In Route Table tab, there must be 2 route tables, one for your private subnets/lambdas and other for public subnets.
    Associate public subnets to route table specified for public subnets with below configuration

     Destination -> 0.0.0.0/0
     Target -> {Internet Gateway}
    
  5. Associate private subnets to other route table with below configuration

     Destination -> 0.0.0.0/0
     Target -> {Nat Gateway}  
    
  6. Create a role with policy AWSLambdaVPCAccessExecutionRole and attach it to all lambdas that need public access.

  7. Create a security group for your lambda functions, You can provide the allowed network configurations for inbound/outbound rules.

    Lambda SG is merely used to restrict the traffic to other resources that its gonna communicate with. It doesn't listen to any port/ip inbound. Like, you specify the lambda SG as the source in an EC2 SG. Now EC2 will allow the traffic coming from that lambda SG only. read more here

  8. Attach VPC, private-subnets and security-group to your lambdas.

Cheers :)

ref

Top comments (0)