-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathinstanceFile.py
More file actions
53 lines (41 loc) · 1.74 KB
/
instanceFile.py
File metadata and controls
53 lines (41 loc) · 1.74 KB
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
#!/usr/bin/env python3
import boto3
import sys
from datetime import datetime, timedelta
ec2 = boto3.resource('ec2')
cloudwatch = boto3.resource('cloudwatch')
# #Lists the number of instances
def list_inst():
for instance in ec2.instances.all():
print (instance.id, instance.state)
# #stops the current instance running
def stop_inst():
try:
for instance in ec2.instances.all():
print (instance.id, instance.state)
response = instance.stop()
print (response)
except Exception:
print('Unable to stop instance!')
# #terminates the current instance
def term_inst():
try:
for instance_id in sys.argv[1:]:
instance = ec2.Instance(instance_id)
response = instance.terminate()
print (response)
except Exception:
print('Unable to terminate!')
#metric check here (add more metrics for cloudwatch monitoring)
def cloudWatch():
instid = input("Please enter instance ID: ")
metric_iterator = cloudwatch.metrics.filter(Namespace='AWS/EC2',
MetricName='CPUUtilization',
Dimensions=[{'Name':'InstanceId', 'Value': instid}])
for metric in metric_iterator:
response = metric.get_statistics(StartTime=datetime.now() - timedelta(minutes=65), # 5 minutes ago
EndTime=datetime.now() - timedelta(minutes=60), # now
Period=300, # 5 minute intervals
Statistics=['Average'])
print ("Average CPU utilisation:", response['Datapoints'][0]['Average'])
# print (response) # for debugging only