import {EC2Client, DescribeInstancesCommand, TerminateInstancesCommand } from "@aws-sdk/client-ec2"; // CONFIGURATION const ec2 = new EC2Client({region: 'us-east-1'}); const maxAge = 1000 * 3600 * 3; // Terminate instances older than 3 hours in millis const tag = 'jenkins'; // Only terminate instances with this tag // if not null, send a notification to Slack/Mattermost if any instances are terminated, // this is an Incoming Webhook URL: const notifyUrl = null; const thresholdDate = new Date((new Date()).getTime() - maxAge); async function notifySlack(message) { /*global fetch*/ await fetch(notifyUrl, { method: 'POST', headers: { 'Accept': 'application/json', 'Content-Type': 'application/json' }, body: JSON.stringify({ "text": message }) }) .then(response => console.log("Response for notification is: " + JSON.stringify(response))) .catch((error) => { console.error('error sending notification', error); }); } export const handler = async(event) => { const data = await ec2.send(new DescribeInstancesCommand({ Filters: [ { Name: "architecture", Values: ["x86_64"] }, { Name: "instance-state-name", Values: ["running"] }, { Name: "tag-key", Values: [tag], }, ], })); var killList = []; var message = "I am killing the following AWS instances that have been running longer than " + maxAge + "ms: "; data.Reservations.forEach(reservation => { reservation.Instances.forEach(instance => { console.log("Checking instance " + instance.InstanceId + " with launch time " + instance.LaunchTime); var instanceLaunchDate = new Date(instance.LaunchTime); if (instanceLaunchDate < thresholdDate) { console.log("Will kill this instance"); killList.push(instance.InstanceId); //find its name var name = "?"; instance.Tags.forEach(tag => { if (tag.Key == 'Name') { name = tag.Value; } }); message += instance.InstanceId + " (" + name + "),"; } }); }); console.log("Final kill list: " + killList); var killResult = {}; if (killList.length > 0) { killResult = await ec2.send(new TerminateInstancesCommand({ InstanceIds: killList })); console.log("Killed instances (" + message + ") with result: " + JSON.stringify(killResult)); if (notifyUrl != null) { await notifySlack(message); } } return { killList: killList, killResult: killResult }; };