Reputation: 183
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:
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();
});
}
Upvotes: 5
Views: 1462
Reputation: 200446
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.
Upvotes: 8