2024-03-08 09:36:27 +08:00
|
|
|
# reference: https://aws.amazon.com/premiumsupport/knowledge-center/start-stop-lambda-eventbridge/
|
2022-06-22 09:49:12 +08:00
|
|
|
import boto3
|
|
|
|
import os
|
|
|
|
import json
|
|
|
|
import time
|
2024-03-12 11:49:02 +08:00
|
|
|
import logging
|
|
|
|
|
|
|
|
logging.basicConfig(
|
|
|
|
format='%(asctime)s %(levelname)-8s %(message)s',
|
|
|
|
level=logging.INFO,
|
|
|
|
datefmt='%Y-%m-%d %H:%M:%S')
|
|
|
|
logger = logging.getLogger(__name__)
|
2022-06-22 09:49:12 +08:00
|
|
|
|
|
|
|
|
2024-03-08 09:36:27 +08:00
|
|
|
def start_instances(instances: list[str]) -> dict:
|
|
|
|
ec2 = boto3.client('ec2', region_name=os.environ['AWS_REGION'])
|
|
|
|
resp = ec2.start_instances(InstanceIds=instances)
|
|
|
|
ec2.close()
|
|
|
|
return resp
|
|
|
|
|
|
|
|
|
|
|
|
def stop_instances(instances: list[str]) -> dict:
|
|
|
|
ec2 = boto3.client('ec2', region_name=os.environ['AWS_REGION'])
|
|
|
|
resp = ec2.stop_instances(InstanceIds=instances)
|
|
|
|
ec2.close()
|
|
|
|
return resp
|
|
|
|
|
|
|
|
|
|
|
|
def instance_status(instances: list[str]) -> str:
|
|
|
|
time.sleep(10)
|
|
|
|
ec2 = boto3.client('ec2', region_name=os.environ['AWS_REGION'])
|
2024-03-08 09:39:33 +08:00
|
|
|
ec2Array: list[dict] = []
|
2024-03-08 09:36:27 +08:00
|
|
|
response = ec2.describe_instances(InstanceIds=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']})
|
|
|
|
ec2.close()
|
|
|
|
return json.dumps(ec2Array)
|
|
|
|
|
2022-06-22 09:49:12 +08:00
|
|
|
|
|
|
|
def lambda_handler(event, context):
|
2024-03-08 09:36:27 +08:00
|
|
|
instances: list[str] = json.loads(os.environ['instances'])
|
|
|
|
if event['action'] == 'start':
|
2024-03-12 11:49:02 +08:00
|
|
|
logger.info('Starting instances: ' + str(instances))
|
2024-03-08 09:36:27 +08:00
|
|
|
resp = start_instances(instances)
|
2024-03-12 11:49:02 +08:00
|
|
|
logger.info(instance_status(instances))
|
2024-03-08 09:36:27 +08:00
|
|
|
elif event['action'] == 'stop':
|
2024-03-12 11:49:02 +08:00
|
|
|
logger.info('Stopping instances: ' + str(instances))
|
2024-03-08 09:36:27 +08:00
|
|
|
resp = stop_instances(instances)
|
2024-03-12 11:49:02 +08:00
|
|
|
logger.info(instance_status(instances))
|
2024-03-08 09:36:27 +08:00
|
|
|
else:
|
|
|
|
resp = "Event action not provided"
|
|
|
|
return resp
|
2022-06-22 09:49:12 +08:00
|
|
|
|