1
votes

I have created AWS Lambda to start and stop EC2 instances hosted in private VPC.

I could deploy the Lambda function in 'NO VPC' and perform action without any issues.

But when I deploy the Lambda function in the private VPC (where my EC2 is located) and 2 different subnets (in one of those subnet EC2 is launched) with necessary security group changes, I got timed out error and could not perform actions anymore.

Question: Is it necessary to add a NAT Gateway to Lambda, though there is no requirement of outer internet?

If yes, please let me know why.

If no, please let me know what else I have to check to get this process working.

1
How are you actually starting and stopping the ec2 instances? - K Mo

1 Answers

2
votes

When making an API call to AWS, the service endpoints are accessible from the Internet. Therefore, issuing a command to Start or Stop an Amazon EC2 instance requires access to the Internet.

If an AWS Lambda function is not configured to use a VPC, then it has access to the Internet by default.

If an AWS Lambda function is configured to use a VPC, and that Lambda function needs to access the Internet, then:

  • Configure the Lambda function to use a private subnet
  • Launch a NAT Gateway in a public subnet and update the private subnet Route Tables to use the NAT Gateway for Internet-bound traffic

Alternatively, you could create a VPC Endpoint for EC2. This allows commands destined for the EC2 service to pass through the VPC Endpoint without going via the Internet. This is commonly done for VPCs that have no Internet Gateway (eg Dev/Test VPCs with no public access).

Finally, have a think about whether the Lambda function actually needs to be connected to a VPC. If it needs to access within the VPC and access the Internet, then you'll need to use one of the above methods. However, if it does not require access to the VPC, then do not connect it to the VPC and it will connect to the internet just fine.