Summary

    Let’s see how easy it is to set up that on the following structure:

    EC2-autoscaling-group

    On this situation, we want to “shut down” the ASG (autoscaling group) containing the Kubernetes Node, which means our application used by the developers. We want to scale the desired number of instances to 0 at night, and setting it back to the desired number during the day.

    We’ll use in this situation the following component (and you might want to terraform them):

    • AWS IAM Role (and its policy)
    • AWS Lambda function
    • AWS CloudWatch Rule

    AWS IAM Role

    First, we’ll need the IAM role necessary for the AWS Lambda. Go to the IAM section and create a policy:

    create-policies-aws
    create-policy-ec2
    lambda-created

    Then, we’ll create the role who’ll use this policy:

    create-lambda-role
    create-role-lambda

    We’ll pass the tag section

    create-role
    lambda-autoscaling-role

    AWS LAMBDA

    Now we need to create the lambda that will start and shutdown your instance inside your autoscaling group, you need to get the id of your autoscaling group, you can find it there:

    create-autoscaling-group

    Write down the Name of your autoscaling group.

    Now create the Lambda that will start and stop your instances:

    basic-info

    Make sure to pick Python 2.7 and your existing role created.

    Then we’ll add the following code to the function code of this lambda:

    function-code

    AWS Cloudwatch Rules

    Then we’ll create both start and stop CloudWatch rules:

    start-rule

    For the cron expression, we are making here the instances start at 06:15:00 GMT, but you can choose another expression.

    With the following parameters (make sure to replace asg_name by your autoscaling name and change aws_region if you are not in eu-west-3)

    rule-details

    Then we need to create the stop instances CloudWatch rule:

    create-rules

    For the cron expression, we are making the instances stop at 20:00:00 GMT, but you can choose another expression.

    With the following parameters (make sure to replace asg_name by your autoscaling name and change aws_region if you are not in eu-west-3)

    stop-autoscaling

     


    By setting the MinSize and DesiredSize to 0, you stop all the instances inside your auto scaling group, set those parameters back to your configuration (here 3), and start back the instances. We now have seen how easily we can stop our EC2 instances at night to save money on our cloud bill. To make sure your autoscaling is done properly, you should monitor your ec2 instance with Cloudwatch.