UPD: revamped code
This commit is contained in:
parent
a474f5f5ef
commit
b47c62f944
|
@ -1,26 +1,47 @@
|
|||
# reference: https://aws.amazon.com/premiumsupport/knowledge-center/start-stop-lambda-eventbridge/
|
||||
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 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'])
|
||||
ec2Array = []
|
||||
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)
|
||||
|
||||
|
||||
def lambda_handler(event, context):
|
||||
instances: list[str] = json.loads(os.environ['instances'])
|
||||
if event['action'] == 'start':
|
||||
resp = start_instances(instances)
|
||||
print(instance_status(instances))
|
||||
elif event['action'] == 'stop':
|
||||
resp = stop_instances(instances)
|
||||
print(instance_status(instances))
|
||||
else:
|
||||
resp = "Event action not provided"
|
||||
return resp
|
||||
|
||||
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
|
||||
|
|
Loading…
Reference in New Issue