1
votes

I'm trying to get a Lambda running inside a public subnet to communicate with the internet. I'm able to get the Lambda to hit www.google.com without a VPC (which the docs say runs one behind the scene) but cannot if I run the Lambda in a VPC.

Repro steps:

  1. Create a Lambda (Node.js 12x) with the follow code. I named the Lambda 'curlGoogle'.
  2. Run it to verify it succeeds and can fetch from www.google.com. There should be no VPC specified.
  3. Go to the VPC Dashboard and use the VPC Wizard to create a VPC with a public subnet. I've tried a view values for IPv4 CIDR block (e.g. 10.1.0.0/16), IPv6 CIDR block, AZ. I usually leave 'Enable DNS hostnames' to Yes.
  4. Change the Lambda to use the newly created VPC, Subnet and Security Group.
  5. Verify this does not reach Google and times out.

I've tried modifications of this approach and haven't had any success (e.g. actually associating the subnet with the vpc, loosening all of settings on the Security Group and Network ACLs).

I originally tried following the one public and one private docs and failed to get that working.

Any ideas? Thanks! - Dan

const http = require('http');

exports.handler = async (event) => {
    return httprequest().then((data) => {
        const response = {
            statusCode: 200,
            body: JSON.stringify(data),
        };
    return response;
    });
};
function httprequest() {
     return new Promise((resolve, reject) => {
        const options = {
            host: 'www.google.com',
            path: '/',
            port: 80,
            method: 'GET'
        };
        const req = http.request(options, (res) => {
          if (res.statusCode < 200 || res.statusCode >= 300) {
                return reject(new Error('statusCode=' + res.statusCode));
            }
            var body = [];
            res.on('data', function(chunk) {
                body.push(chunk);
            });
            res.on('end', function() {
                try {
                    body = Buffer.concat(body).toString();
                } catch(e) {
                    reject(e);
                }
                resolve(body);
            });
        });
        req.on('error', (e) => {
          reject(e.message);
        });
        // send the request
       req.end();
    });
}
1
Does your VPC have a NAT Gateway?hephalump
In one of the configurations. I described that lower in a reply to Mark B.Dan Hill

1 Answers

2
votes

AWS Lambda functions are never assigned a public IP address when in a VPC, even if they are in a public subnet. So they can never access the Internet directly when running in a VPC. You have to place Lambda functions in a private subnet with a route to a NAT Gateway in order to give them access to the Internet from within your VPC.