Last active
February 11, 2024 02:26
-
-
Save jsbonso/5dc80d6fb57118d475eb3f314b52e699 to your computer and use it in GitHub Desktop.
Dynamic Start and Stop Scheduler Lambda Functions
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import boto3, os, json, time | |
REGION = os.environ['REGION'] | |
ASG_NAME = os.environ['ASG_NAME'] | |
SSM_PARAMETER_NAME = os.environ['SSM_PARAMETER_NAME'] | |
ssm = boto3.client('ssm', region_name=REGION) | |
ec2 = boto3.client('ec2', region_name=REGION) | |
autoscaling = boto3.client('autoscaling', region_name=REGION) | |
def lambda_handler(event, context): | |
# get parameter_store instance id value | |
INSTANCE_ID = ssm.get_parameter(Name=SSM_PARAMETER_NAME)['Parameter']['Value'] | |
#start instance | |
ec2.start_instances( | |
InstanceIds=[INSTANCE_ID] | |
) | |
#wait until instance is in Running state | |
waiter_running = ec2.get_waiter('instance_running') | |
waiter_running.wait( | |
InstanceIds=[INSTANCE_ID] | |
) | |
print('INFO: Started ' + INSTANCE_ID) | |
#wait until instance health is OK | |
waiter_healthcheck = ec2.get_waiter('instance_status_ok') | |
waiter_healthcheck.wait( | |
InstanceIds=[INSTANCE_ID] | |
) | |
print('INFO: Instance ' + INSTANCE_ID + ' is healthy...') | |
time.sleep(60) | |
#set instance to InService | |
autoscaling.exit_standby( | |
InstanceIds=[INSTANCE_ID], | |
AutoScalingGroupName=ASG_NAME | |
) | |
#wait until LifecycleState is InService | |
response = autoscaling.describe_auto_scaling_instances( | |
InstanceIds=[INSTANCE_ID] | |
) | |
while str(json.dumps(response["AutoScalingInstances"][0]["LifecycleState"])).replace('"', '') != "InService": | |
time.sleep(60) | |
response = autoscaling.describe_auto_scaling_instances( | |
InstanceIds=[INSTANCE_ID] | |
) | |
print('INFO: Instance set to InService...') | |
# set desired capacity to 1 | |
autoscaling.set_desired_capacity( | |
AutoScalingGroupName=ASG_NAME, | |
DesiredCapacity=1 | |
) | |
print('INFO: Set desired capacity to 1...') |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment