Skip to content

Commit 425ac3f

Browse files
committed
Feat: Auto Shutdown EC2 Lambda
1 parent 0417940 commit 425ac3f

3 files changed

Lines changed: 48 additions & 0 deletions

File tree

python/aws-lambda-power-on-off-ec2/README.md

Whitespace-only changes.
Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
import boto3
2+
import botocore
3+
import DateTime
4+
import json
5+
6+
## initiate EC2 via Boto3
7+
8+
ec2 = boto3.client('ec2', region_name='ap-southeast-3')
9+
10+
11+
12+
def lambda_handler(event=None, context=None):
13+
14+
instances = []
15+
16+
ec2_results = ec2.describe_instances()
17+
#ec2_start = ec2.start_instances(InstanceIds=[instances])
18+
#ec2_stop = ec2.stop_instances(InstanceIds=[instances])
19+
20+
21+
for reservation in ec2_results['Reservations']:
22+
for instance in reservation['Instances']:
23+
instance_id = instance['InstanceId']
24+
state = instance['State']['Name']
25+
26+
name = None
27+
for tag in instance.get('Tags', []):
28+
if tag['Key'] == 'Name' :
29+
name = tag['Value']
30+
break
31+
32+
instances.append({
33+
'InstanceId': instance_id,
34+
'Name': name,
35+
'Status': state,
36+
})
37+
38+
return {
39+
'StatusCode': 200,
40+
'body': instances
41+
}
42+
43+
if __name__ == "__main__":
44+
response = lambda_handler()
45+
print(json.dumps(response, indent=2))
Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
botocore==1.42.1
2+
boto3==1.42.1
3+
DateTime

0 commit comments

Comments
 (0)