-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmenu_driven_script_for_ec2_actions.py
51 lines (46 loc) · 2 KB
/
menu_driven_script_for_ec2_actions.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
import boto3
import sys
import time
# "Global" variables, used to log in to AWS, use the EC2 service in US-east-1, and fetch the instance data before passing any commands to AWS
aws_mag_con=boto3.session.Session(profile_name='terraform')
ec2_con_re=aws_mag_con.resource(service_name="ec2",region_name='us-east-1')
ec2_con_cli=aws_mag_con.client(service_name="ec2",region_name='us-east-1')
response=ec2_con_cli.describe_instances()['Reservations']
# Print out each instance with some status info to avoid having to manually open up the AWS console
for each_item in response:
print("Printing instances...")
for each in each_item['Instances']:
print("==================================")
print('Instance ID: {}\nInstance monitoring: {}\nInstance state: {}'.format(each['InstanceId'],each['Monitoring'],each['State']))
# While loop cycles through the options until the user selects 4, invoking sys.exit()
while True:
print("This script performs the following actions on an EC2 instance:")
print("""
1. Start
2. Stop
3. Terminate
4. Exit""")
opt=int(input("Enter your option: "))
if opt == 1:
instance_id=input("Enter your instance ID: ")
my_req_instance=ec2_con_re.Instance(instance_id)
# Displays functions available for use with the defined instance:
# print(dir(my_req_instance))
print("Starting EC2 instance")
my_req_instance.start()
elif opt == 2:
instance_id=input("Enter your instance ID: ")
my_req_instance=ec2_con_re.Instance(instance_id)
my_req_instance.stop()
print("Stopping EC2 instance")
elif opt == 3:
instance_id=input("Enter your instance ID: ")
my_req_instance=ec2_con_re.Instance(instance_id)
my_req_instance.terminate()
print("Terminating EC2 instance")
elif opt == 4:
time.sleep(10)
sys.exit()
else:
print("Your option is invalid. Please select a valid option.")
time.sleep(5)