AWS Step-by-Step

Reducing Your AWS Costs Through Instance Scheduling, Part 2: Test Early

It's a good idea to test your work just to make sure that everything is working properly because if problems exist, it will be easier to diagnose and correct them now than later.

In the previous article, I explained that your organization may be able to realize significant cost savings by shutting down virtual machine (VM) instances when they are not in use. One way of doing this is to schedule VM instances to automatically be powered down at the end of the day and powered back up in the morning.

So far, we have set up the necessary permissions, applied a tag to a VM instance, and created a Lambda function. Before we continue on though, it's a good idea to test your work just to make sure that everything is working properly. If problems exist, then it will be easier to diagnose and correct those problems now than to do it later on.

Testing Your Work
Before you continue with setting everything up, this is a good time to test your work to make sure that everything is going to function properly. The Lambda function that you have created will only work if Lambda has the necessary permissions. To make sure that the appropriate permissions exist, create an EC2 instance (if necessary) and apply whatever tags that you have decided to use to that instance. Now, make sure that the instance has been powered down, go back to the screen shown in the figure above, and click the Test button. This will cause Lambda to display the Configure Test Event screen.

Select the Create New Event option and then give the test event a name, such as StartEC2Test, as shown in Figure 1. Now, click Save and then click Test. This will manually invoke the Lambda function.

Figure 1: You don't have to worry about configuring most of the options shown on this screen.
[Click on image for larger view.] Figure 1: You don't have to worry about configuring most of the options shown on this screen.

As I was writing this article, I had a lot of problems with the testing process displaying a time-out error, like the one shown in Figure 2. If this happens, try repeating the test two or three times. At that point, one of two things will likely happen. Either the test will continue to time out, but the instance will start or else you will eventually receive a message stating that Lambda lacks the necessary permissions.

Figure 2: You may receive a time out error when testing the function.
[Click on image for larger view.] Figure 2: You may receive a time out error when testing the function.

Adding Code to the EC2SchedulerOff Function
Earlier, you created a Lambda function called EC2ScheduleOff. However, that function does not yet do anything. That being the case, you are going to need to add some code to the function. To do so, go to the main Lambda screen, click on Functions, and then click on the EC2SchedulerOff function. Now, select the Code tab and replace any existing code with this code:

import boto3
def lambda_handler(event, context):
    ec2 = boto3.client('ec2')
    filters = [{'Name': 'tag:Schedule', 'Values': ['BusinessHours']}]
    instances = ec2.describe_instances(Filters=filters)
    for reservation in instances['Reservations']:
        for instance in reservation['Instances']:
            ec2.stop_instances(InstanceIds=[instance['InstanceId']])
            print(f"Stopped instance: {instance['InstanceId']}")

Once again, you are going to need to modify this code to reflect the tags that you have used in your own organization.

Configuring CloudWatch
Now that the Lambda functions have been created, the last thing that you need to do is to configure CloudWatch to invoke the functions on a scheduled basis. Open the CloudWatch console, expand the Events tab, and then click Rules. This will cause the Define Rule Detail screen to be displayed.

At the bottom of this screen, you will see a Rule Type option. Set the Rule Type to Schedule. When you do, you may see a message telling you that you can use EventBridge for scheduling purposes. However, I am going to continue in CloudWatch. Enter a name for the rule (for example, you might call the rule StartInstance) and then click the Continue to Create Rule button.

Now, you will need to enter the scheduled start time as a CRON expression. If for example, you want the instance to start at 7:00 AM then you would enter the CRON expression as 0 7 * * ? *. You can see an example of this in Figure 3. It's worth noting that AWS defaults to scheduling the events based on UTC time. If you want the schedule to reflect the local time zone, you will need to choose that option instead.

Figure 3: You will need to enter the start time as a CRON expression.
[Click on image for larger view.] Figure 3: You will need to enter the start time as a CRON expression.

Click Next, and you will be taken to the Select Targets screen. Set the target to Lambda Function and then choose EC2SchedulerOn from the list of functions, as shown in Figure 4. Click Next to continue.

Figure 4: You will need to point CloudWatch to your Lambda function.
[Click on image for larger view.] Figure 4: You will need to point CloudWatch to your Lambda function.

Click Next and you will be taken to the Tags screen. You don't have to do anything here, so click Next one more time and then click the Create Rule button to create the CloudWatch rule. Now, repeat the process and create an additional rule for shutting down the VM instance at your desired time.

About the Author

Brien Posey is a 22-time Microsoft MVP with decades of IT experience. As a freelance writer, Posey has written thousands of articles and contributed to several dozen books on a wide variety of IT topics. Prior to going freelance, Posey was a CIO for a national chain of hospitals and health care facilities. He has also served as a network administrator for some of the country's largest insurance companies and for the Department of Defense at Fort Knox. In addition to his continued work in IT, Posey has spent the last several years actively training as a commercial scientist-astronaut candidate in preparation to fly on a mission to study polar mesospheric clouds from space. You can follow his spaceflight training on his Web site.

Featured

Subscribe on YouTube