{ "AWSTemplateFormatVersion": "2010-09-09", "Description": "Automatically stop EC2 instances that have a specific tag highlighed by Trusted Advisor using Amazon Cloudwatch events and AWS Lambda", "Metadata": { "LICENSE": "Copyright 2017 Amazon Web Services, Inc. or its affiliates. All Rights Reserved. This file is licensed to you under the AWS Customer Agreement (the \"License\"). You may not use this file except in compliance with the License. A copy of the License is located at http://aws.amazon.com/agreement/ . This file is distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, express or implied. See the License for the specific language governing permissions and limitations under the License." }, "Resources": { "LambdaIAMRole": { "Type": "AWS::IAM::Role", "Properties": { "AssumeRolePolicyDocument": { "Version": "2012-10-17", "Statement": [ { "Effect": "Allow", "Principal": { "Service": "lambda.amazonaws.com" }, "Action": "sts:AssumeRole" } ] }, "Path": "/", "Policies": [ { "PolicyName": "TAEC2InstanceStop", "PolicyDocument": { "Version": "2012-10-17", "Statement": [ { "Sid": "LambdaLogging", "Effect": "Allow", "Action": [ "logs:CreateLogGroup", "logs:CreateLogStream", "logs:PutLogEvents" ], "Resource": [ "arn:aws:logs:*:*:*" ] }, { "Sid": "Ec2Actions", "Action": [ "ec2:StopInstances", "ec2:DescribeTags" ], "Effect": "Allow", "Resource": "*" } ] } } ] } }, "LambdaFunction": { "Properties": { "Code": { "ZipFile": { "Fn::Join": [ "\n", [ "// Sample Lambda Function to get Trusted Advisor Low Utilization Amazon EC2 Instances check details from Cloudwatch events and execute the EC2 stop instance recommendation", "var AWS = require('aws-sdk');", "", "// define configuration", "const tagKey ='environment';", "const tagValue ='dev';", "const dryRun =true; //set to true during testing ", "const regionSpecification = 'us-east-1'; //Specify a region to restrict the EC2 Stop Instances action to. Use 'all' for all regions", "", "//main function which gets Trusted Advisor data from Cloudwatch event", "exports.handler = (event, context, callback) => {", " //extract details from Cloudwatch event", " checkName = event.detail['check-name'];", " instanceId = event.detail['check-item-detail']['Instance ID'];", " region = event.detail['check-item-detail']['Region/AZ'].slice(0, -1);", " const trustedAdvisorSuccessMessage = `Successfully got details from Trusted Advisor check, ${checkName} and executed automated action.`;", " //check if the EC2 instance is in the right region", " if (region == regionSpecification || regionSpecification == 'all') { stopInstances(instanceId, region); }", " else { console.log ('No EC2 instance found in specifed region'); }", " callback(null, trustedAdvisorSuccessMessage); //return success", "};", "", "//Sample function which stops EC2 Instances after checking their tags", "function stopInstances (instanceId, region) {", " AWS.config.update({region: region});", " var ec2 = new AWS.EC2();", " //get tags for the instances highlighted by Trusted Advisor", " var describeTagsparams = {", " Filters: [", " {", " Name: 'resource-id',", " Values: [instanceId]", " },", " {", " Name: 'key',", " Values: [tagKey]", " }", " ]", " };", " ec2.describeTags(describeTagsparams, function(err, data) {", " if (err) console.log(err, err.stack); // an error occurred", " else {", " if (data.Tags == '') {data = {Tags: [{value: 'empty'}]} };", " //if the tag value matches what's configured, then stop the instance", " if (data.Tags[0].Value == tagValue)", " {", " var stopInstancesParams = {", " InstanceIds: [instanceId],", " DryRun: dryRun //set to true for testing", " };", " ec2.stopInstances(stopInstancesParams, function(err, data) {", " if (err) console.log(instanceId, region, err, err.stack); // an error occurred", " else console.log('Instance stopped: ', instanceId, region); // successful response", " });", " }", " else console.log ('Instance did not match tag: ', instanceId, region);", " }", " });", "}", "" ] ] } }, "Description": "Stop EC2 instances that have a specific tag in response to Trused Advisor", "Handler": "index.handler", "Role": { "Fn::GetAtt": [ "LambdaIAMRole", "Arn" ] }, "Runtime": "nodejs10.x", "Timeout": 60 }, "Type": "AWS::Lambda::Function" }, "LambdaPermission": { "Type": "AWS::Lambda::Permission", "Properties": { "FunctionName": { "Fn::GetAtt": [ "LambdaFunction", "Arn" ] }, "Action": "lambda:InvokeFunction", "Principal": "events.amazonaws.com", "SourceArn": { "Fn::GetAtt": [ "CloudWatchEventRule", "Arn" ] } } }, "CloudWatchEventRule": { "Type": "AWS::Events::Rule", "Properties": { "Description": "Low Utilization Amazon EC2 Instances", "EventPattern": { "source": [ "aws.trustedadvisor" ], "detail-type": [ "Trusted Advisor Check Item Refresh Notification" ], "detail": { "status": [ "WARN" ], "check-name": [ "Low Utilization Amazon EC2 Instances" ] } }, "State": "ENABLED", "Targets": [ { "Arn": { "Fn::GetAtt": [ "LambdaFunction", "Arn" ] }, "Id": "StopTAEC2Instances" } ] } } } }