Using boto in an AWS lambda function in a VPC

amazon-lambdaamazon-vpcamazon-web-servicesboto

I have a lambda that accesses EC2. I want to assign it to a VPC for security purposes, but when I do boto just stops working. Here's a minimal example:

ec2 = boto3.resource('ec2', region_name='eu-west-2')
instances = ec2.instances.filter(Filters=[
  {
    'Name': 'vpc-id',
    'Values': [vpc_id]
  }
])
for instance in instances:
  # function hangs here
  print(instance)

The Lambda's role has the neccessary permissions on ec2, and works fine outside the VPC. When I put the lambda in the VPC (in a security group that allows all outbound traffic), it hangs. What do I need to do?

Best Answer

The issue was that I needed to have a NAT on the subnet the Lambda function is running in - an Internet Gateway is not enough!

I'm assuming that this is because the Lambda runs only privately, and the Internet Gateway, allowing 2-way traffic, would not allow routes to/from the Lambda.

Adding the Lambda to a private subnet with a NAT attached fixed this problem.