-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathec2_rollbacker.py
129 lines (115 loc) · 4.81 KB
/
ec2_rollbacker.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
import boto3
##Ability to restore from snapshots alot faster. This script DOESNT restore multiple instances,
##but this script can be ran in parallel with other instances of this script in order to restore
##multiple instances
def getSnapshotsList(client, instance):
snapshotInfo = []
print("Retrieving Snapshots")
snapshots = client.describe_snapshots(Filters = [{"Name" : "status", "Values" : ["completed"]}], OwnerIds=['self'])["Snapshots"]
for s in snapshots:
description = s["Description"]
createTime = s["StartTime"]
snapshotID = s["SnapshotId"]
volumeSize = s["VolumeSize"]
try:
tags = s["Tags"]
for t in tags:
if t["Key"] == "Name":
tagInfo = t["Value"]
except:
pass
if instance in description or instance in tagInfo:
snapshotInfo.append({"CreateTime" : createTime, "SnapshotID" : snapshotID, "VolumeSize" : volumeSize})
print("Creation Time: {} | SnapshotID: {} | VolumeSize: {}" .format(createTime, snapshotID, volumeSize))
return snapshotInfo
def getInstances(client):
instanceInfo = []
instances = client.describe_instances()
for i in instances["Reservations"]:
instanceID = i["Instances"][0]["InstanceId"]
az = i["Instances"][0]["Placement"]["AvailabilityZone"]
tags = i["Instances"][0]["Tags"]
for t in tags:
if t["Key"] == "Name":
instanceName = t["Value"]
instanceInfo.append({"InstanceID" : instanceID, "InstanceName" : instanceName , "AZ" : az})
return instanceInfo
def createVolume(client, az, SnapshotId):
vol_status = client.create_volume(
AvailabilityZone=az,
SnapshotId=SnapshotId,
VolumeType="gp2"
)
return vol_status["VolumeId"]
def shutdownServer(client, instanceID):
print("STOPPING INSTANCE {}...".format(instanceID))
client.stop_instances(
InstanceIds=[instanceID]
)
w = client.get_waiter('instance_stopped')
w.wait(InstanceIds=[instanceID])
print("INSTANCE {} IS STOPPED".format(instanceID))
def volumeActions(client, instanceID, volumeFromSnapshot_ID):
instance = client.describe_instances(InstanceIds=[instanceID])
mounts = instance["Reservations"][0]["Instances"][0]["BlockDeviceMappings"]
aval_volumes = []
print("This instance has the following mounts")
for b in mounts:
volumeID = b["Ebs"]["VolumeId"]
vol_describe = client.describe_volumes(VolumeIds=[volumeID])
try:
tags = vol_describe["Volumes"][0]["Tags"]
for t in tags:
if t["Key"] == "Name":
desc = t["Value"]
except KeyError:
desc = "No Tags Defined"
print("VolumeID: {} | Mount: {} | NAME-Tag: {}".format(volumeID, b["DeviceName"], desc))
aval_volumes.append(volumeID)
vol_mount_id = input("Choose the volumeID to unmount: ")
while vol_mount_id not in aval_volumes:
vol_mount_id = input("Your selection is invalid, select a VolumeID listed above:")
vol_mount = input("Enter New Mount Point to use: ")
detach_response = client.detach_volume(
InstanceId=instanceID,
VolumeId=volumeID
)
if detach_response["ResponseMetadata"]["HTTPStatusCode"] != 200:
print("There was an issue deattaching the volume... HTTP ERROR: ")
print(detach_response["ResponseMetadata"]["HTTPStatusCode"])
exit(1)
print("Deattching Old Volume...")
w = client.get_waiter('volume_available')
w.wait(VolumeIds=[vol_mount_id])
attachResponse = client.attach_volume(
InstanceId=instanceID,
VolumeId=volumeFromSnapshot_ID,
Device=vol_mount
)
print("Attaching New Volume...")
if attachResponse["ResponseMetadata"]["HTTPStatusCode"] != 200:
print("There was an issue attaching the volume... HTTP ERROR: ")
print(detach_response["ResponseMetadata"]["HTTPStatusCode"])
exit(1)
print("BOOTING UP INSTANCE...")
client.start_instances(
InstanceIds=[instanceID]
)
def main():
client = input("Select a PROFILE in the AWS Config: ")
region = ""
if region == "":
region = "us-east-1"
session = boto3.Session(profile_name=client, region_name=region)
client = session.client('ec2')
listOfInstnaces = getInstances(client)
for l in listOfInstnaces:
print("InstanceID: {} | InstanceName : {} | AZ : {}".format(l["InstanceID"], l["InstanceName"], l["AZ"]))
instance = input("Please Select an InstanceID: ")
AZ = input("Select the AZ you want the volume to be in: ")
getSnapshotsList(client, instance)
snapshot = input("Select A Snapshot: ")
volID = createVolume(client, AZ, snapshot)
shutdownServer(client, instance)
volumeActions(client, instance, volID)
main()