-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsnippet-dump.py
142 lines (97 loc) · 4.25 KB
/
snippet-dump.py
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
#Gets the instance state and checks to ensure it's
resp = ec2.describe_instance_status(
InstanceIds=[str(instance_id)],
IncludeAllInstances=True)
#print("Response = ",resp)
instance_status = resp['InstanceStatuses'][0]['InstanceState']['Code']
#print("Instance status =", instance_status)
if instance_status == 80:
#Try a dry run first to test permissions
try:
ec2.start_instances(InstanceIds=[instance_id], DryRun=True)
except ClientError as e:
if 'DryRunOperation' not in str(e):
raise
# Dry run succeeded, run start_instances without dryrun
try:
response = ec2.start_instances(InstanceIds=[instance_id], DryRun=False)
print(response)
except ClientError as e:
print(e)
#Example Script
import boto3
import time
# Defining boto3 the connection
ec2 = boto3.resource('ec2')
def timeInRange(startRange, endRange, currentRange):
if startRange <= endRange:
return startRange <= currentRange <= endRange
else:
return startRange <= currentRange or currentRange <= endRange
def lambda_handler(event, context):
currentTime = time.strftime("%H:%M")
filters = [{
'Name': 'tag:autoSchedulerEnabled',
'Values': ['True']
}
]
instances = ec2.instances.filter(Filters=filters)
stopInstancesList = []
startInstancesList = []
for instance in instances:
for tag in instance.tags:
if tag['Key'] == 'autoStopSchedule':
stopTime = tag['Value']
pass
if tag['Key'] == 'autoStartSchedule':
startTime = tag['Value']
pass
pass
instanceState = instance.state['Name']
if timeInRange(startRange=startTime, endRange=stopTime, currentRange=currentTime):
if (instanceState == "running") or (instanceState == "pending"):
print("[", currentTime, "]", "Instance", instance.id, "already running, it won't be added to START list")
else:
startInstancesList.append(instance.id)
print("[", currentTime, "]", "Instance", instance.id, "has been added to START list")
pass
elif timeInRange(startRange=startTime, endRange=stopTime, currentRange=currentTime) == False:
if (instanceState == "stopped") or (instanceState == "stopping"):
print("[", currentTime, "]", "Instance", instance.id, "already stopped, it won't be added to STOP list")
else:
stopInstancesList.append(instance.id)
print("[", currentTime, "]", "Instance", instance.id, "has been added to STOP list")
pass
pass
if len(stopInstancesList) > 0:
stop = ec2.instances.filter(InstanceIds=stopInstancesList).stop()
print(stop)
else:
print("[", currentTime, "]", "No instances to stop in the list")
if len(startInstancesList) > 0:
start = ec2.instances.filter(InstanceIds=startInstancesList).start()
print(start)
else:
print("[", currentTime, "]", "No instances to start in the list")
#Get and stop all running instances with env tag
import boto3
ec2 = boto3.resource('ec2',"ap-south-1")
# filter all running instances
instances = ec2.instances.filter(Filters=[{'Name': 'instance-state-name', 'Values': ['running']}])
# Decleared list to store running instances
all_running_instances = []
specific_tag = 'env'
for instance in instances:
# store all running instances
all_running_instances.append(instance)
# Instances with specific tags
if instance.tags != None:
for tags in instance.tags:
# Instances with tag 'env'
if tags["Key"] == specific_tag:
# Remove instances with specefic tags from all running instances
all_running_instances.remove(instance)
#print(all_running_instances)
for specific in all_running_instances:
print(specific)
specific.stop()