DEV Community

Cover image for [AWS Experiment] 2 - Lambda in Private Subnets
Sunbeom Kweon (Ben)
Sunbeom Kweon (Ben)

Posted on • Updated on

[AWS Experiment] 2 - Lambda in Private Subnets

Experiment goal: Can we use AWS Lambda functions in our private subnets?

const https = require('https');

exports.handler = (event, context, callback) => {
    const https = require('https');

    https.get('https://encrypted.google.com/', (res) => {
      console.log('statusCode:', res.statusCode);
      console.log('headers:', res.headers);

      res.on('data', (d) => {
        process.stdout.write(d);
      });

    }).on('error', (e) => {
      console.log("Error");
      console.error(e);
    });
};
Enter fullscreen mode Exit fullscreen mode

Lambda function code to check the internet connection (Node js)

aws lambda invoke --function-name vpc-lambda-2 out --log-type Tail --query 'LogResult' --output text --region us-west-1 | base64 -d
Enter fullscreen mode Exit fullscreen mode

A bash command to invoke the Lambda function from an EC2 instance.

First Experiment - Can we invoke a Lambda function in a private subnet from an EC2 instance in a public subnet?

Launches

  • I deployed an EC2 instance in a public subnet to connect through AWS console.

  • I deployed a Lambda function inside of the private subnet, with a route table without any internet gateway route specified.

Attaching roles

  • The EC2 instance has an attached role of LambdaFullAccess

  • I attached AWSLambdaVPCAccessExecutionRole to the Lambda function, which gives it a permission to manage elastic network interfaces to connect your function to a virtual private cloud (VPC).

Image description

Attached policies of the Lambda function.

Private subnet's routing table

There is no IGW configured for 0.0.0.0/0 in private subnet.

  • ...and I was able to invoke a Lambda function from an EC2 instance in the different subnet(public), because of AWSLambdaVPCAccessExecutionRole that I attached to the Lambda function.

  • And at the same time, I was able to confirm there is no internet access, which is an intended situation.

No internet access

Lambda function has been fired, but there was no internet connection

Second Experiment - Accessing the internet from the Lambda function

  1. NAT
  2. VPC Endpoint

1. Using NAT

  • I created a NAT attached Elastic IP and associated with the public subnet.

NAT

Updated the routing table of the private subnet.

Result

Lambda function successfully reached out the internet.

2. Using VPC Endpoint

...update later

Conclusion

Top comments (0)