How to schedule EC2 instances to stop and start automatically
Since AWS charges for running hours only, we can reduce the cost by shutting down the EC2 instances when not required.
This article explains the steps to enable EC2 instances to stop and start automatically using Lambda functions and Cloudwatch.
Step1: Login to AWS console.
Step2: Open IAM dashboard.
Step3: Choose Policies from left menu and Create a new IAM policy with the following json.
{
"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": "*"
}
]
}
Step4: Choose Roles from left menu and Create a new role for Lambda and attach the policy that created earlier.
Step5: Open Lambda Dashboard.
Step6: Create the Lambda function to stop the EC2 instance and use the following Python code.
import boto3
region = 'aws-region'
instances = ['instance-id1', 'instance-id-2']
ec2 = boto3.client('ec2', region_name=region)
def lambda_handler(event, context):
ec2.stop_instances(InstanceIds=instances)
print('stopped your instances: ' + str(instances))
Where aws-region, instance-id1 and instance-id2 need to be replaced with the region where the AWS resources located and the ids of the EC2 instances that need to be stopped respectively.
Please note to use the newly created IAM role as the execution role and Python3.8 as the run-time.
Step7: Deploy the Lambda function.
Step8: Create the Lambda function to start the EC2 instance and use the following Python code.
import boto3
region = 'aws-region'
instances = ['instance-id1', 'instance-id-2']
ec2 = boto3.client('ec2', region_name=region)
def lambda_handler(event, context):
ec2.start_instances(InstanceIds=instances)
print('started your instances: ' + str(instances))
Where aws-region, instance-id1 and instance-id2 need to be replaced with the region where the AWS resources located and the ids of the EC2 instances that need to be stopped respectively.
Please note to use the newly created IAM role as the execution role and Python3.8 as the runtime.
Step9: Deploy the Lambda function.
Step10: Open the Cloudwatch console.
Step11: In the left navigation pane, under Events, choose Rules.
Step12: Select Create rule.
Step13: Choose Schedule under Event Source
Step14: Enter the cron expression according to the requirement.
Cron Fields: Minutes Hours Day-of-month Month Day-of-week Year
Step15: Choose Add target under Targets.
Step16: Choose Lambda function and select the function that we have created for stopping the EC2 instances.
Step17: Choose Configure details.
Step18: Put the Name and Description for the rule.
Step19: Select the Enabled check box and Create rule.
Step20: Repeat the steps 11 to 15 for creating the event to start the EC2 instances.
That's all...