-
Notifications
You must be signed in to change notification settings - Fork 117
/
Copy pathTAStopLowUtilizationEC2Instances.template
196 lines (195 loc) · 9.63 KB
/
TAStopLowUtilizationEC2Instances.template
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
{
"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"
}
]
}
}
}
}