I want to reduce my Amazon EC2 usage by stopping and starting instances at predefined times or utilization thresholds. Can I configure AWS Lambda and Amazon CloudWatch to help me do that automatically?

You can use a CloudWatch Event to trigger a Lambda function to start and stop your EC2 instances at scheduled intervals.

Amazon CloudWatch Events allows you to create an event that is triggered at a specified time or interval in response to events that take place in your account. For example, you can create a CloudWatch event for a specific time of day, or you can create an alarm when CPU utilization for an instance reaches a specific threshold. You can also configure a Lambda function to start and stop instances when triggered by these CloudWatch events.

In this example, we use Lambda functions to start and stop EC2 instances, and then we use CloudWatch events that start your instances in the morning and stop the instances at night.

1.    Open the AWS Lambda console and choose Create a Lambda function.

2.    Choose Blank Function from the available blueprints.

3.    Choose Configure triggers, and then choose Next. (You will configure a Lambda trigger later.)

4.    Enter the following information to configure your Lambda function:
       Enter the name Name, such as "StopEC2Instances".
       Enter the Description, such as "stops EC2 instances every day at night”.
       Chooose Python 2.7 as your Runtime.

5.    To stop your instances, run a command similar to the following:

import boto3
# Enter the region your instances are in. Include only the region without specifying Availability Zone; e.g., 'us-east-1'
region = 'XX-XXXXX-X'
# Enter your instances here: ex. ['X-XXXXXXXX', 'X-XXXXXXXX']
instances = ['X-XXXXXXXX']

def lambda_handler(event, context):
    ec2 = boto3.client('ec2', region_name=region)
    ec2.stop_instances(InstanceIds=instances)
    print 'stopped your instances: ' + str(instances)

6.    Expand the Role drop-down menu and choose Create a custom role. This should open a new tab or window in your browser.

7.    Enter the following information to create a role for Lambda to use:
       Under IAM Role, choose Create a new IAM Role.
       For Role Name, enter “lambda_start_stop_ec2” or another name that’s meaningful to you.

8.    Choose View Policy Document, Edit, and then edit the policy as follows:

{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Effect": "Allow",
      "Action": [
        "logs:CreateLogGroup",
        "logs:CreateLogStream",
        "logs:PutLogEvents"
      ],
      "Resource": "arn:aws:logs:*:*:*"
    },
    {
      "Effect": "Allow",
      "Action": [
        "ec2:Start*",
        "ec2:Stop*"
      ],
      "Resource": "*"
    }
  ]
}

9.    Choose Allow.

10.   From Advanced settings, input 10 seconds for the function timeout.
Note: Environment variables, dead letter queues, and VPC are not necessary for this example; however, if you wish to use these features, you need to add additional permissions. See the AWS Lambda documentation for more details.

11.   Choose Next to review your function configuration, and then choose Create function.

12.   Repeat steps 1-4 and 9 to create another function that starts your instances again, using code similar to the following:

import boto3
# Enter the region your instances are in. Include only the region without specifying Availability Zone; e.g.; 'us-east-1'
region = 'XX-XXXXX-X'
# Enter your instances here: ex. ['X-XXXXXXXX', 'X-XXXXXXXX']
instances = ['X-XXXXXXXX']

def lambda_handler(event, context):
    ec2 = boto3.client('ec2', region_name=region)
    ec2.start_instances(InstanceIds=instances)
    print 'started your instances: ' + str(instances)

Note: Use a Name and Description that show this function is used to start instances. You can use the previously created role.

Test your newly created functions

1.    From the Lambda console, choose Functions, select your function, and then choose Test.

2.    Your function doesn’t use the test event, so from the Input test event editor just choose Save and test.

Create a CloudWatch event that triggers your Lambda function at night

1.    Open the CloudWatch console.

2.    Choose Events, and then choose Create rule.

3.    Select Schedule under Event Selector.

4.    Enter an interval of time or cron expression that tells Lambda when to stop your instances; for more information on the correct syntax, see Schedule Expression Syntax for Rules.
Note: Cron expressions are evaluated in UTC. Make sure to adjust for your preferred time zone.

5.    Choose Add target.

6.    Under Targets, choose Lambda function.

7.    For Function, choose the Lambda function that stops your instances.

8.    Choose Configure details.

9.    Enter the following information in the provided fields:
       For Name, enter "StopEC2Instances", or another name that’s meaningful to you.
       For Description, add a meaningful description; for example, “stops EC2 instances every day at night”.
       For State, check Enabled.

10.   Choose Create rule.

To restart your instances in the morning, repeat these steps using your preferred time.


Did this page help you? Yes | No

Back to the AWS Support Knowledge Center

Need help? Visit the AWS Support Center.

Published: 2016-07-07

Updated: 2017-08-23