AWS Lambda to shut down SSH inactive EC2 instances using System Manager

Posted: December 14, 2018 in Amazon Web Services (AWS), Scripts

In this post we configured Windows instances to go to hibernation. In this one we’ll modify Node.JS script to shut down EC2 instances if no one is connected via SSH connections.

Setting SSH idle timeout settings

cat /etc/profile.d/ssh-timeout.sh
export TMOUT=900
readonly TMOUT

Reboot

 

Installing SSM Agent on CentOS 7

yum install -y https://s3.amazonaws.com/ec2-downloads-windows/SSMAgent/latest/linux_amd64/amazon-ssm-agent.rpm
systemctl status amazon-ssm-agent
systemctl enable amazon-ssm-agent
systemctl start amazon-ssm-agent

How to create SSM role and how to assign it to instance check out here. and here

Create following tags:

 

Capture

 

Change only code in auto_stop/modules/control/index.js

// Import Dependencies
let AWS = require('aws-sdk');
AWS.config.region = "eu-west-1";

module.exports.getInstanceIds = () => {
return new Promise(
(resolve, reject) => {
let ec2 = new AWS.EC2();
let params = {
Filters: [
{ Name: "instance-state-name",
Values: ["running"]
},
{
Name: "tag:Auto_Stop_Schedule",
Values: ["1"]
},
{
Name: "tag:Auto_Stop_Enabled",
Values: ["True","true", "Yes", "yes"]
},
{
Name: "tag:Auto_Stop_Type",
Values: ["Linux","linux"]
}
]
};

ec2.describeInstances(params, (err, data) => {
if (err) reject(err);

let instanceIds = [];
let reservations = "";
try {
reservations = data.Reservations;
}
catch(err) {
reject(err);
}
if(Array.isArray(reservations)) {
reservations.forEach((reservation) => {
reservation.Instances.forEach((instance) =>{
instanceIds.push(instance.InstanceId);
});
});
if(instanceIds.length >= 1) {
resolve(
{
"InstanceIds": instanceIds
}
);
}
else {
console.log("[Info] getInstanceIds: No instances found.");
resolve();
}
}
else {
reject(new Error("[Error] getInstanceIds: Reservations is not an array."));
}
});
}
);
};

module.exports.shutdownInstances = (controlObj) => {
return new Promise(
(resolve, reject) => {
let ssm = new AWS.SSM();

let instanceIds = controlObj.InstanceIds;
instanceIds.forEach((i) => {
let ssmParams = {
InstanceIds: [i],
DocumentName: "AWS-RunShellScript",
Parameters: {
"workingDirectory":[""],
"executionTimeout":["300"],
"commands":["#!/bin/bash","LOGFOLDER=\"/var/log/ssh_check\"","LOGFILE=\"auto_stop_activity.log\"","","# Check if the ssh_check Log dir exists. If not, create it.","[ -d $LOGFOLDER ] || mkdir -p $LOGFOLDER","","if [[ \"$(/usr/bin/w | wc -l)\" -gt 2 ]];"," then"," echo \"$(date) >>> Live SSH session detected\" "," echo \"$(date) >>> Live SSH session detected\" >> \"$LOGFOLDER/$LOGFILE\""," else"," # If no active SSH sessions are found, shutdown the instance."," echo \"$(date) >>> No running sessions detected\" "," echo \"$(date) >>> Shutting down...\"",""," echo \"$(date) >>> No running sessions detected\" >> \"$LOGFOLDER/$LOGFILE\" "," echo \"$(date) >>> Shutting down...\" >> \"$LOGFOLDER/$LOGFILE\" "," shutdown -P -t 30 > /dev/null 2>&1"," exit 0"," fi"]
},
MaxErrors: "0",
TimeoutSeconds: 120
}

// Hibernate instances
ssm.sendCommand(ssmParams, function(err, data) {
if (err) {
console.log(`Error: ${err}`);
}
console.log("Command Sent");
console.log(`Instance to shutdown: ${instanceIds}`);
});
});
}
);
};

 

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s