Last active
October 12, 2023 20:08
-
-
Save oliversalzburg/ff39f48e3e519a7343f6300e24a72291 to your computer and use it in GitHub Desktop.
AWS VPC Lambda Connectivity Test
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import dns from "node:dns/promises"; | |
import https from "node:https"; | |
import url from "node:url"; | |
const SERVICES = [ | |
"dynamodb", | |
"execute-api", | |
"glue", | |
"lambda", | |
"s3", | |
"sns", | |
"states", | |
"sync-states", | |
]; | |
const TEST_HOSTS = [ | |
...SERVICES.map( | |
(service) => `${service}.${process.env.AWS_REGION}.amazonaws.com` | |
), | |
`google.com`, | |
]; | |
const lookup = async (name) => { | |
try { | |
const result = await dns.lookup(name); | |
return { message: `DNS : ${name} → ${result.address}` }; | |
} catch (error) { | |
return { error, message: `DNS : ${name} → <error>` }; | |
} | |
}; | |
const get = async (address) => { | |
const result = await new Promise((resolve) => { | |
const errorResolver = (error) => { | |
resolve({ error, statusCode: "<error>" }); | |
}; | |
try { | |
const request = https.get(address, { timeout: 5000 }, (response) => { | |
response | |
.on("data", Function.prototype) | |
.on("end", () => resolve({ statusCode: response.statusCode })) | |
.on("error", errorResolver); | |
}); | |
request.on("error", errorResolver).on("timeout", () => { | |
request.off("error", errorResolver); | |
request.on("error", Function.prototype); | |
request.destroy(); | |
resolve({ statusCode: "<timeout>" }); | |
}); | |
} catch (error) { | |
errorResolver(error); | |
} | |
}); | |
return { | |
error: result.error, | |
message: `HTTP: ${address} → ${result.statusCode}`, | |
}; | |
}; | |
export const handler = async (_event) => { | |
const resultHandler = (result) => | |
result.error | |
? console.log(result.message) || | |
console.error(`└-X-> ${result.error.name}: ${result.error.message}`) | |
: console.log(result.message); | |
for (const host of TEST_HOSTS) { | |
await lookup(host).then(resultHandler); | |
} | |
for (const host of TEST_HOSTS) { | |
await get(`https://${host}/`).then(resultHandler); | |
} | |
}; | |
// Auto-invoke outside of Lambda context. | |
if (import.meta.url.startsWith("file:")) { | |
const modulePath = url.fileURLToPath(import.meta.url); | |
if (process.argv[1] === modulePath) { | |
handler(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment