-
Notifications
You must be signed in to change notification settings - Fork 1
/
app.py
139 lines (108 loc) · 4.3 KB
/
app.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
from flask import Flask, request, jsonify
from config import config
import logging
import boto3
app = Flask(__name__)
logging.basicConfig(
filename=config['log_file'],
level=config['log_level']
)
def get_aws_client(request):
aws_access_key_id = request.args.get("aws_access_key_id")
aws_secret_access_key = request.args.get("aws_secret_access_key")
region_name = request.args.get("region_name")
return boto3.client('ec2',
aws_access_key_id=aws_access_key_id,
aws_secret_access_key=aws_secret_access_key,
region_name=region_name
)
# Endpoint: http://<api_host>:<api_port>/ec2/list
@app.route('/ec2/list', methods=['GET'])
def aws_list():
try:
client = get_aws_client(request)
instances = client.describe_instances()
output = []
for reservation in instances['Reservations']:
for instance in reservation['Instances']:
output.append(
{
'id': instance['InstanceId'],
"instance-type": instance['InstanceType'],
"instance-state": instance['State']['Name'],
"private-ip": instance['PrivateIpAddress'],
"key-name": instance['KeyName'],
"image-id": instance['ImageId'],
"vpc-id": instance['VpcId'],
"subnet-id": instance['SubnetId'],
"security-group-ids": instance['SecurityGroups'],
}
)
print(output)
return jsonify(output), 200
except Exception as error:
print(str(error))
return jsonify({'Message': "Unexpected Error occured", 'Error': str(error)}), 500
# Endpoint: http://<api_host>:<api_port>/ec2/start
@app.route("/ec2/start", methods=["POST"])
def start_ec2_instances():
try:
client = get_aws_client(request)
InstanceId = request.args.get("InstanceId")
response = client.start_instances(
InstanceIds=[InstanceId]
)
return jsonify(response["StartingInstances"][0]), 200
except Exception as error:
print(str(error))
return jsonify({'Message': "Unexpected Error occured", 'Error': str(error)}), 500
# Endpoint: http://<api_host>:<api_port>/ec2/stop
@app.route("/ec2/stop", methods=["POST"])
def stop_ec2_instances():
try:
client = get_aws_client(request)
InstanceId = request.args.get("InstanceId")
response = client.stop_instances(
InstanceIds=[InstanceId]
)
return jsonify(response["StoppingInstances"][0]), 200
except Exception as error:
print(str(error))
return jsonify({'Message': "Unexpected Error occured", 'Error': str(error)}), 500
# Endpoint: http://<api_host>:<api_port>/ec2/create
@app.route("/ec2/create", methods=["POST"])
def create_ec2_instance():
try:
client = get_aws_client(request)
KeyName = request.args.get("KeyName")
SecurityGroupIds = request.args.get("SecurityGroupId")
response = client.run_instances(
ImageId='ami-0fb653ca2d3203ac1', # Ubuntu Server 20.04, 64-bit x86
InstanceType='t2.micro', # 1 vCPU, 1 GB RAM (Free tier ^^)
MinCount=1,
MaxCount=1,
KeyName=KeyName,
SecurityGroupIds=[SecurityGroupIds]
)
print(response)
return jsonify(response["Instances"][0]), 200
except Exception as error:
print(str(error))
return jsonify({'Message': "Unexpected Error occured", 'Error': str(error)}), 500
# Endpoint: http://<api_host>:<api_port>/ec2/terminate
@app.route("/ec2/terminate", methods=["POST"])
def terminate_ec2_instance():
try:
client = get_aws_client(request)
InstanceId = request.args.get("InstanceId")
response = client.terminate_instances(
InstanceIds=[InstanceId]
)
return jsonify(response["TerminatingInstances"][0]), 200
except Exception as error:
print(str(error))
return jsonify({'Message': "Unexpected Error occured", 'Error': str(error)}), 500
if __name__ == "__main__":
app.run(host=config["host"],
port=config["port"],
debug=False)