Skip to content

Instantly share code, notes, and snippets.

@KarolKski
Last active April 28, 2023 05:18
Show Gist options
  • Save KarolKski/cee58f8ad3cd0be0af0586e145503c35 to your computer and use it in GitHub Desktop.
Save KarolKski/cee58f8ad3cd0be0af0586e145503c35 to your computer and use it in GitHub Desktop.
AWS Lambda handler for checking expiration date of SSL certificates
const fs = require('fs');
const axios = require('axios');
const checkCertExpiration = require('check-cert-expiration');
const twilioClient = require('twilio')(accountSid, authToken);
const accountSid = process.env.TWILIO_ACCOUNT_SID // Your Account SID from www.twilio.com/console
const authToken = process.env.TWILIO_AUTH_TOKEN // Your Auth Token from www.twilio.com/console
const phoneNumber = process.env.MOBILE_NUMBER_SMS // Phonenumber to send SMS to
const ourNumber = process.env.TWILIO_OUR_NUMBER // Phonenumber to send SMS from
const endpointChatUrl = process.env.ROCKET_LOG_URL // RocketChat webhook URL for sending messages to chat
const daysNotify = process.env.DAYS_NOTIFY_BEFORE_EXPIRE // Days to notify before SSL expires and sent as chat message
const daysNotifySMS = process.env.DAYS_NOTIFY_BEFORE_EXPIRE_SMS // Days to notify before SSL expires and sent as SMS
const sentSMS = async (logMessage) => {
try {
await twilioClient.messages.create({
body: `${logMessage}`,
from: ourNumber,
to: phoneNumber
});
} catch (err) {
console.log(err);
}
}
//check if ssl is about to expire
const checkSSL = async (domain) => {
try {
const { daysLeft, host, port } = await checkCertExpiration(domain);
let logMessage = `${daysLeft} days until the certificate expires for ${host}`;
if(daysLeft < daysNotifySMS){
console.log(logMessage);
await sentSMS(logMessage);
await axios.get(`${endpointChatUrl}${logMessage}`);
}else if(daysLeft <= daysNotify){
console.log(`${logMessage}`);
await axios.get(`${endpointChatUrl}${logMessage}`);
}
} catch (err) {
console.error(`${domain}: ${err.name}:${err.message}`);
}
}
const checkAllDomains = async () => {
// get domains from domains
const domains = fs.readFileSync('./domains', 'utf8').split('\n');
for (let i = 0; i < domains.length; i++) {
const domain = domains[i];
await checkSSL(domain);
}
}
async function testLocal(){
await checkAllDomains();
}
exports.handler = async function(event, context, callback) {
await checkAllDomains();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment