Last active
August 19, 2020 18:08
-
-
Save BhanukaUOM/fdfcf316b52d512b11c6833f05e6aa2b to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import sys | |
import time | |
import json | |
import boto3 | |
import pyperclip | |
from retrying import retry | |
lightsail_client = boto3.client('lightsail') | |
instance_name = 'My-Instance' | |
instance_snapshot_name = 'My-Instance-Snapshot' | |
availability_zone = 'ap-southeast-1a' | |
blueprint_id = 'windows_server_2016' | |
bundle_id = 'medium_win_2_0' | |
user_data = """<powershell> | |
Set-MpPreference -DisableRealtimeMonitoring $true | |
Set-ExecutionPolicy Bypass -Scope Process -Force; [System.Net.ServicePointManager]::SecurityProtocol = [System.Net.ServicePointManager]::SecurityProtocol -bor 3072; iex ((New-Object System.Net.WebClient).DownloadString('https://chocolatey.org/install.ps1')) | |
choco install -y GoogleChrome notepadplusplus git nodejs-lts vscode filezilla vlc python winrar | |
</powershell>""" | |
def export_rdp_file(public_ip, username): | |
file = open("connect.rdp", "w") | |
file.write(f'full address:s:{public_ip}') | |
file.write(f'\nusername:s:{username}') | |
file.close() | |
def export_credential_file(public_ip, username, password): | |
with open('credentials.json', 'w') as fp: | |
json.dump({ | |
'public_ip': public_ip, | |
'username': username, | |
'password': password | |
}, fp) | |
def import_credential_file(): | |
try: | |
with open('credentials.json') as f: | |
data = json.load(f) | |
return data | |
except FileNotFoundError: | |
return {} | |
def create_instance(): | |
print('Creating Lightsail Instance') | |
try: | |
response = lightsail_client.create_instances( | |
instanceNames=[instance_name], | |
availabilityZone=availability_zone, | |
blueprintId=blueprint_id, | |
bundleId=bundle_id, | |
userData=user_data | |
) | |
print('Creating Lightsail Instance Success') | |
return response | |
except Exception as e: | |
print('Error Occupied when Creating Lightsail Instance') | |
raise e | |
def create_instance_from_snapshot(): | |
print('Creating Lightsail Instance from Snapshot') | |
try: | |
response = lightsail_client.create_instances_from_snapshot( | |
instanceNames=[instance_name], | |
availabilityZone=availability_zone, | |
bundleId=bundle_id, | |
instanceSnapshotName=instance_snapshot_name | |
) | |
print('Creating Lightsail Instance from Snapshot Success') | |
return response | |
except Exception as e: | |
print('Error Occupied when Creating Lightsail Instance from Snapshot') | |
raise e | |
def delete_instance(): | |
print('Deleting Lightsail Instance') | |
try: | |
response = lightsail_client.delete_instance( | |
instanceName=instance_name, | |
forceDeleteAddOns=True | |
) | |
print('Deleting Lightsail Instance Success') | |
return response | |
except Exception as e: | |
print('Error Occupied when Deleting Lightsail Instance') | |
raise e | |
def get_instance(): | |
print('Getting Lightsail Instance') | |
try: | |
response = lightsail_client.get_instance( | |
instanceName=instance_name | |
) | |
print('Getting Lightsail Instance Success') | |
return response | |
except Exception as e: | |
print('Error Occupied when Getting Lightsail Instance') | |
raise e | |
def create_instance_snapshot(): | |
print('Creating Lightsail Instance Snapshot') | |
try: | |
response = lightsail_client.create_instance_snapshot( | |
instanceSnapshotName=instance_snapshot_name, | |
instanceName=instance_name | |
) | |
print('Creating Lightsail Instance Snapshot Success') | |
return response | |
except Exception as e: | |
print('Error Occupied when Creating Lightsail Instance Snapshot') | |
raise e | |
def delete_instance_snapshot(): | |
print('Deleting Lightsail Instance Snapshot') | |
try: | |
response = lightsail_client.delete_instance_snapshot( | |
instanceSnapshotName=instance_snapshot_name | |
) | |
print('Deleting Lightsail Instance Snapshot Success') | |
return response | |
except Exception as e: | |
print('Error Occupied when Deleting Lightsail Instance Snapshot') | |
raise e | |
def get_instance_snapshot(logs=True): | |
if logs: | |
print('Getting Lightsail Instance Snapshot') | |
try: | |
response = lightsail_client.get_instance_snapshot( | |
instanceSnapshotName=instance_snapshot_name | |
) | |
if logs: | |
print('Getting Lightsail Instance Snapshot Success') | |
return response | |
except Exception as e: | |
if logs: | |
print('Error Occupied when Getting Lightsail Instance Snapshot') | |
raise e | |
@retry(wait_fixed=60000) | |
def wait_till_instance_snapshot_available(): | |
print('Waiting till Instance Snapshot Available') | |
snapshot_info = get_instance_snapshot(False) | |
if snapshot_info['instanceSnapshot']['state'] != 'available': | |
raise Exception('Snapshot Still Creating') | |
print('Created Lightsail Instance Snapshot Available') | |
@retry(wait_fixed=40000) | |
def get_instance_access_details(check_password=True, logs=True): | |
if logs: | |
print('Getting Lightsail Instance Access Details') | |
try: | |
response = lightsail_client.get_instance_access_details( | |
instanceName=instance_name | |
) | |
if check_password and not response['accessDetails']['password']: | |
if logs: | |
print('Instance is Starting. Please Wait...') | |
raise Exception('Instance is Starting. Please Wait...') | |
print('Getting Lightsail Instance Access Details Success') | |
return response['accessDetails']['ipAddress'], response['accessDetails']['username'], response['accessDetails']['password'] | |
except lightsail_client.exceptions.OperationFailureException: | |
if logs: | |
print('Instance is Starting. Please Wait...') | |
raise e | |
except Exception as e: | |
if logs: | |
print('Error Occupied when Getting Lightsail Instance Access Details') | |
raise e | |
argvs = sys.argv | |
if len(argvs) < 2: | |
print('Please Specify Argument.', 'stop or start') | |
elif argvs[1] == 'start': | |
try: | |
create_instance_from_snapshot() | |
except lightsail_client.exceptions.NotFoundException: | |
print('Instance Snapshot Not Found.', 'Creating New Instance') | |
try: | |
create_instance() | |
try: | |
public_ip, username, password = get_instance_access_details() | |
print('\n-------------- Instance Access Details -------------') | |
print('| Public IP:\t', public_ip) | |
print('| Username:\t', username) | |
print('| Password:\t', password) | |
print('-----------------------------------------------------\n') | |
export_rdp_file(public_ip, username) | |
export_credential_file(public_ip, username, password) | |
pyperclip.copy(password) | |
sys.exit() | |
except lightsail_client.exceptions.OperationFailureException: | |
print('Instance Already Exists\n\n') | |
except lightsail_client.exceptions.InvalidInputException: | |
print('Instance Already Exists\n\n') | |
except Exception as e: | |
print(e) | |
print('Instance Already Exists\n\n') | |
public_ip, username, password = get_instance_access_details(False) | |
credentials = import_credential_file() | |
if 'password' in credentials: | |
password = credentials['password'] | |
print('\n-------------- Instance Access Details -------------') | |
print('| Public IP:\t', public_ip) | |
print('| Username:\t', username) | |
print('| Password:\t', password) | |
print('-----------------------------------------------------\n') | |
export_credential_file(public_ip, username, password) | |
export_rdp_file(public_ip, username) | |
pyperclip.copy(password) | |
sys.exit() | |
print(instance) | |
elif argvs[1] == 'stop': | |
try: | |
get_instance() | |
except Exception as err: | |
print(str(err)) | |
sys.exit() | |
try: | |
delete_instance_snapshot() | |
time.sleep(5) | |
except lightsail_client.exceptions.NotFoundException: | |
print('Snapshot Not Found') | |
try: | |
create_instance_snapshot() | |
except lightsail_client.exceptions.InvalidInputException: | |
print('Instance Already Exists\n\n') | |
wait_till_instance_snapshot_available() | |
delete_instance() | |
else: | |
print('Invalid Argument.', 'Specify stop or start') |
Available Scripts
-
Start Instance
python main.py start
-
Stop Instance
python main.py stop
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
requirments.txt