File tree Expand file tree Collapse file tree
python/aws-lambda-power-on-off-ec2 Expand file tree Collapse file tree Original file line number Diff line number Diff line change 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 ))
Original file line number Diff line number Diff line change 1+ botocore==1.42.1
2+ boto3==1.42.1
3+ DateTime
You can’t perform that action at this time.
0 commit comments