forked from bstocker/API_Driven
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlambda_function.py
More file actions
61 lines (50 loc) · 2.21 KB
/
Copy pathlambda_function.py
File metadata and controls
61 lines (50 loc) · 2.21 KB
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
import json
import boto3
import os
# LocalStack requires us to explicitly point to its internal endpoint
LOCALSTACK_HOSTNAME = os.environ.get("LOCALSTACK_HOSTNAME", "localhost")
ENDPOINT_URL = f"http://{LOCALSTACK_HOSTNAME}:4566"
ec2_client = boto3.client("ec2", endpoint_url=ENDPOINT_URL, region_name="us-east-1")
def lambda_handler(event, context):
print("Received event:", json.dumps(event))
# Handle both direct JSON payloads and stringified API Gateway proxy payloads
body = event.get("body", "{}")
if isinstance(body, str):
try:
body = json.loads(body)
except Exception:
return {
"statusCode": 400,
"body": json.dumps({"error": "Invalid JSON format in request body"})
}
action = body.get("action") # 'start' or 'stop'
instance_id = body.get("instance_id")
if not action or not instance_id:
return {
"statusCode": 400,
"body": json.dumps({"error": "Missing 'action' or 'instance_id' in payload"})
}
try:
if action.lower() == "start":
response = ec2_client.start_instances(InstanceIds=[instance_id])
current_state = response['StartingInstances'][0]['CurrentState']['Name']
message = f"Instance {instance_id} is turning on. Current state: {current_state}"
elif action.lower() == "stop":
response = ec2_client.stop_instances(InstanceIds=[instance_id])
current_state = response['StoppingInstances'][0]['CurrentState']['Name']
message = f"Instance {instance_id} is shutting down. Current state: {current_state}"
else:
return {
"statusCode": 400,
"body": json.dumps({"error": f"Unsupported action: {action}. Use 'start' or 'stop'"})
}
return {
"statusCode": 200,
"headers": {"Content-Type": "application/json"},
"body": json.dumps({"status": "success", "message": message})
}
except Exception as e:
return {
"statusCode": 500,
"body": json.dumps({"error": str(e)})
}