Skip to content

Commit a9c9daf

Browse files
committed
[20 May 2026] - Feat: Autoshutdown-lambda
1 parent f8a9f3c commit a9c9daf

2 files changed

Lines changed: 169 additions & 0 deletions

File tree

Lines changed: 71 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,71 @@
1+
import boto3
2+
import logging
3+
import os
4+
5+
# Set up logging
6+
logger = logging.getLogger()
7+
logger.setLevel(logging.INFO)
8+
9+
def lambda_handler(event, context):
10+
action = event.get("action", "").lower()
11+
if action not in ["start", "stop"]:
12+
return {"statusCode": 400, "body": f"Invalid action: {action}. Use 'start' or 'stop'."}
13+
14+
# Gather data from all supported formats
15+
# 1. 'regions' dictionary format: {"us-east-1": ["i-1"], "us-west-2": ["i-2"]}
16+
region_to_ids = event.get("regions", {})
17+
18+
# 2. Singular/List formats (backward compatibility)
19+
instance_id = event.get("instance_id")
20+
instance_ids = event.get("instance_ids", [])
21+
default_region = event.get("region") or os.environ.get("AWS_REGION", "us-east-1")
22+
23+
# Consolidate backward compatibility inputs into the mapping
24+
if instance_id or instance_ids:
25+
all_ids = set(instance_ids)
26+
if instance_id:
27+
all_ids.add(instance_id)
28+
29+
if default_region not in region_to_ids:
30+
region_to_ids[default_region] = []
31+
region_to_ids[default_region].extend(list(all_ids))
32+
33+
if not region_to_ids:
34+
return {"statusCode": 400, "body": "Missing instance IDs or regions"}
35+
36+
results = []
37+
errors = []
38+
39+
for region, ids in region_to_ids.items():
40+
if not ids:
41+
continue
42+
43+
try:
44+
logger.info(f"Performing action '{action}' on instances in {region}: {ids}")
45+
ec2 = boto3.client('ec2', region_name=region)
46+
47+
if action == "start":
48+
ec2.start_instances(InstanceIds=ids)
49+
elif action == "stop":
50+
ec2.stop_instances(InstanceIds=ids)
51+
52+
results.append({
53+
"region": region,
54+
"status": f"Successfully {'started' if action == 'start' else 'stopped'}",
55+
"instance_ids": ids
56+
})
57+
except Exception as e:
58+
err_msg = f"Error in {region}: {str(e)}"
59+
logger.error(err_msg)
60+
errors.append(err_msg)
61+
62+
status_code = 200 if not errors else (207 if results else 500)
63+
64+
return {
65+
"statusCode": status_code,
66+
"body": {
67+
"action": action,
68+
"results": results,
69+
"errors": errors
70+
}
71+
}
Lines changed: 98 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,98 @@
1+
# How to use
2+
3+
### Prerequisites
4+
- AWS Lambda Function
5+
- AWS IAM Role
6+
- AWS EventBridge Schedule Rule
7+
8+
### Create Lambda Function
9+
There are 2 way to create lambda function:
10+
11+
1. Using AWS CLI
12+
```
13+
aws lambda create-function --function-name <your-function-name> --architectures arm64 --handler lambda_function.lambda_handler --timeout 90 --memory-size 128 --ephemeral-storage 512 --runtime python3.14 --logging-config '{"LogFormat": "Text"}' --zip-file <code-in-zip>
14+
```
15+
16+
2. Using AWS Console
17+
1. Go to AWS Lambda
18+
2. Click on Create function
19+
3. Click on Author from scratch
20+
4. Fill in the function name, runtime, and architecture
21+
5. Click on Create function then copy-paste the code to the code editor
22+
6. Click on Deploy
23+
7. Copy the Function ARN for EventBridge Schedule Rule
24+
25+
### Create IAM Role
26+
1. Go to AWS IAM
27+
2. Click on Roles
28+
3. Click on Create role
29+
4. Select AWS service
30+
5. Select Lambda
31+
6. Click on Next
32+
7. Select the policies that you want to attach to the role
33+
```
34+
## Policies
35+
- AWSLambdaBasicExecutionRole
36+
- AmazonEC2FullAccess
37+
```
38+
8. Click on Next
39+
9. Click on Create role
40+
41+
### Create EventBridge Schedule Rule
42+
1. Go to AWS EventBridge
43+
2. Click on Rules
44+
3. Click on Create rule
45+
4. Fill in the rule name and description
46+
5. Select the schedule
47+
6. On Invoke part, there will be payload, you can copy-paste the example below:
48+
49+
## For start action
50+
```
51+
{
52+
//for multi region setup, just add more regions and instance ids
53+
"regions": {
54+
"ap-southeast-1": ["i-12345667890abcdef"],
55+
"ap-southeast-3": ["i-0987654321abcdef"]
56+
},
57+
"action": "start"
58+
}
59+
```
60+
61+
## For stop action
62+
```
63+
{
64+
//for multi region setup, just add more regions and instance ids
65+
"regions": {
66+
"ap-southeast-1": ["i-12345667890abcdef"],
67+
"ap-southeast-3": ["i-0987654321abcdef"]
68+
},
69+
"action": "stop"
70+
}
71+
```
72+
73+
7. Click on Next
74+
8. Select the target
75+
9. Click on Create rule
76+
77+
### Test Scheduler
78+
79+
To test the scheduler, try to adjust the time to 1 minute and then check the CloudWatch logs to see if the scheduler is working properly. After the test is completed, remember to change the time back to the desired time.
80+
81+
### Test Lambda Function
82+
To test lambda function manually
83+
1. Go to AWS Lambda
84+
2. Click on your function
85+
3. Click on Test
86+
4. Fill in the payload (make sure the instance id is correct or use the example below)
87+
## Example Payload
88+
```
89+
{
90+
"regions": {
91+
"ap-southeast-1": ["i-045516eb48d2b3bb6"],
92+
"ap-southeast-3": ["i-030c4658d67fc7b9e","i-07651f8193d6a9f6b","i-0285904670b7934d5"]
93+
},
94+
"action": "stop"
95+
}
96+
```
97+
5. Click on Test
98+
6. Check the result for error

0 commit comments

Comments
 (0)