From 2078cd844a2383f53ea743d237e57068487d6144 Mon Sep 17 00:00:00 2001 From: x p k Date: Wed, 22 Jun 2022 09:49:12 +0800 Subject: [PATCH] NEW: ec2 start stop script --- aws/lambda-ec2StartStop.py | 26 ++++++++++++++++++++++++++ 1 file changed, 26 insertions(+) create mode 100644 aws/lambda-ec2StartStop.py diff --git a/aws/lambda-ec2StartStop.py b/aws/lambda-ec2StartStop.py new file mode 100644 index 0000000..84cb509 --- /dev/null +++ b/aws/lambda-ec2StartStop.py @@ -0,0 +1,26 @@ +import boto3 +import logging +import os +import json +import time + +# reference: https://aws.amazon.com/premiumsupport/knowledge-center/start-stop-lambda-eventbridge/ + +ec2 = boto3.client('ec2', region_name=os.environ['region_name']) + +def lambda_handler(event, context): + + ec2.start_instances(InstanceIds=json.loads(os.environ['instances'])) + time.sleep(5) + print("Instance state after lambda execution:") + + ec2Array = [] + response = ec2.describe_instances(InstanceIds=json.loads(os.environ['instances'])) + for r in response['Reservations']: + for i in r['Instances']: + for t in i['Tags']: + if t['Key'] == 'Name': + ec2Array.append({'id': i['InstanceId'], 'name': t['Value'], 'state': i['State']['Name']}) + + print(json.dumps(ec2Array)) + return ec2Array