AWS ASG Desired Capacity Scheduling Using Lambda and EventBridge Scheduler

Pre-Production servers ( ex: Development and staging servers ) should not be running outside of development hours, as this wastes resources and incurs unnecessary costs. Scheduling these servers to be up only when needed can save significant amounts of money, especially for organizations with large server infrastructure

Setup AWS Lambda

Logging to AWS Console and search Lambda. Let’s create the function

Type a name and choose runtime language as python

Create the lambda function and go in to the function.

Please Deploy this python code in to the lambda function

Github : https://github.com/NadunOvitigala/aws-asg-timebase-lambda-code

import boto3

def lambda_handler(event, context):
    

    autoscaling = boto3.client('autoscaling')
    
    auto_scaling_group_name = event['AutoScalingGroupName']
    
    desired_capacity = autoscaling.describe_auto_scaling_groups(AutoScalingGroupNames=[auto_scaling_group_name])['AutoScalingGroups'][0]['DesiredCapacity']
    
    desired_capacity = event['DesiredCapacity']
    
    autoscaling.set_desired_capacity(AutoScalingGroupName=auto_scaling_group_name, DesiredCapacity=desired_capacity)
    
    return {
        'statusCode': 200
    }

After deploy that code go to Configuration > Permissions

Click on the IAM role name and attached ASG Full permission to the IAM role

Setup EventBridge Scheduler

Type EventBridge on search bar and found the scheduler on left-hand side. Click on the create scheduler.

Type name for the Scheduler

In the Schedule pattern you have to setup corn expression

EX: this corn expression for every day 6.00 am will trigger

Flexible time window = OFF

Go NEXT

In the Select Target Please choose Lambda

In the invoke section select the lambda function that your create above and pass the json parameters for the lambda

EX : This parameters for every day 6.00 am turn desired capacity for 1 in ASG

{
  "AutoScalingGroupName": "lamba-timebased",
  "DesiredCapacity": 1
}

Others options are should be default values and finally you can create the EventBridge Sheduler

Note : For Decrease the desired capacity on out of working time you can create a another EventBridge and pass the json value like bellow,

{
  "AutoScalingGroupName": "lamba-timebased",
  "DesiredCapacity": 0
}

Thank You!!

1 thought on “AWS ASG Desired Capacity Scheduling Using Lambda and EventBridge Scheduler”

Leave a Comment

Your email address will not be published. Required fields are marked *