Skip to content

Instantly share code, notes, and snippets.

@pictolearn
Created May 31, 2019 14:25
Show Gist options
  • Save pictolearn/408267cab387c2d5d03a3da30e790ae1 to your computer and use it in GitHub Desktop.
Save pictolearn/408267cab387c2d5d03a3da30e790ae1 to your computer and use it in GitHub Desktop.
python code to launch,list and terminate EC2 instances
import boto3 # a development kit package in AWS
import os # package which runs shell commands
import time # package which handles date and time
def get_ec2_con_for_give_region(my_region): # function definition to get region
ec2_con_re=boto3.resource('ec2',region_name=my_region)
return ec2_con_re
def list_instances_on_my_region(ec2_con_re): # function definition to get instance in that respective region
for each in ec2_con_re.instances.all():
print(each.id)
def get_instant_state(ec2_con_re,in_id): # function definition to get the state of instances in that respective region
for each in ec2_con_re.instances.filter(Filters=[{'Name':'instance-id',"values":[in_id]}]):
pr_st=each.state['Name']
return pr_st
def start_instance(ec2_con_re,in_id): # function for starting or launching an instance
pr_st=get_instant_state(ec2_con_re,in_id)
# if instances are already in a run state
if pr_st=="running":
print("instance is already running")
else:
for each in ec2_con_re.instances.filter(Filters=[{'Name':'instance-id',"values":[in_id]}]):
each.start()
print("please wait it is goiong to start,once if it is started then we will let you know")
each.wait_untilrunning()
print("noe it is running")
return
def Thank_you():
print("\n\n*******************Thank You******************")
return none
def stop_instance(ec2_con_re,in_id): # Function which stops the instance, by getting the id of respective instance
pr_st=get_instant_state(ec2_con_re,in_id)
# if the mentioned instance have already terminated
if pr_st=="stopped":
print("Instance is already stop")
else:
for each in ec2_con_re.instances.filter(Filters=[{'Name':'instance-id',"values":[in_id]}]):
each.stop()
print("please wait it is going to stop")
each.wait_until_stopped()
print("now it stopped")
def welcome():
print("this helps in start and stop of ec2")
time.sleep(3)
def main(): # main function for basic tasks(inputs and other such stuffs)
welcome()
my_region=input("enter your region name:")
print("please wait")
ec2_con_re=get_ec2_con_for_give_region(my_region)
print("please wait listing instances in your region {}.format(my_region)")
list_instances_on_my_region(ec2_con_re)
in_id=input("noe choose instance id to start or stop")
start_stop=input("enter either start or stop")
while True:
if start_stop not in ["start","stop"]:
start_stop = input("enter only start or stop")
continue
else:
break
if start_stop == "start":
start_instance(ec2_con_re,in_id)
else:
stop_instance(ec2_con_re,in_id)
Thank_you()
if__name__== '__main__':
os.system('cls')
main
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment