Last active
February 11, 2024 02:27
-
-
Save jsbonso/292b1fe21347cb0a6df474baa6459c5a to your computer and use it in GitHub Desktop.
Dynamic Start and Stop Lambda Scheduler 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) | |
autoscaling = boto3.client('autoscaling', region_name=REGION) | |
ec2 = boto3.client('ec2', 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'] | |
# set instance to standby | |
autoscaling.enter_standby( | |
InstanceIds=[INSTANCE_ID], | |
AutoScalingGroupName=ASG_NAME, | |
ShouldDecrementDesiredCapacity=True | |
) | |
# wait until LifecycleState is Standby | |
response = autoscaling.describe_auto_scaling_instances( | |
InstanceIds=[INSTANCE_ID] | |
) | |
while str(json.dumps(response["AutoScalingInstances"][0]["LifecycleState"])).replace('"', '') != "Standby": | |
time.sleep(60) | |
response = autoscaling.describe_auto_scaling_instances( | |
InstanceIds=[INSTANCE_ID] | |
) | |
print('INFO: Instance set to standby...') | |
# set desired capacity to 0 to ensure autoscaled instances are cleared | |
autoscaling.set_desired_capacity( | |
AutoScalingGroupName=ASG_NAME, | |
DesiredCapacity=0 | |
) | |
print('INFO: Set desired capacity to 0...') | |
#stop instance | |
ec2.stop_instances( | |
InstanceIds=[INSTANCE_ID] | |
) | |
print('INFO: Stopped ' + INSTANCE_ID) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment