Cloud Automation — Stop and Start EC2 instances in a specific Schedule
Automation is one of the important aspects in cloud infrastructure which enable organizations utilize the resources efficiently and save the money by powering off the computing resources. Particularly in development and test environments, compute capacity (like ec2 instance and database servers) are not used out of office hours and over the weekends. So it makes sense to turn off those unused resources and save cost for the company .
In this blog, we will develop a lambda function which will be scheduled by event bridge rule. Depending upon the tag set up and rule, the lambda function will stop and start the resources in the desired schedule. The solution flow is very simple and available below.
Step -1: Create a lambda function, search lambda in aws management console. Select lambda, click on the create function.
Step -2: Give the details of the lambda function. Select author from Scratch
1. Give the function name
2. Select the run time, here we selected the python 3.8 version
3. In permissions, select a role (here we already created IAM role for lambda which have access to full permission to Lambda and ec2 instance)
4. Click on create function
Step-3: In the code source section, paste the below code and click on deploy to save the code.
import sys
import boto3
import json
from datetime import datetime
tag_key = ‘stop_flag’
tag_value = ‘Yes’
def lambda_handler(event, context):
ec2_client = boto3.client(service_name=”ec2",region_name=’eu-west-2')
response = ec2_client.describe_instances(Filters=[{‘Name’: ‘tag:’+ tag_key, ‘Values’: [tag_value]}])
data = response[‘Reservations’]
for record in data:
instance_data = record[‘Instances’][0]
instance_id = instance_data[‘InstanceId’]
instance_state = instance_data[‘State’][‘Name’]
if instance_state == ‘running’:
print(f’[{datetime.now().strftime(“%d-%b-%Y %H:%M:%S”)}] : Stopping the EC2 instances start — {instance_id}’)
ec2_response = ec2_client.stop_instances(InstanceIds= [instance_id])
response_code = ec2_response[‘ResponseMetadata’][‘HTTPStatusCode’]
if response_code == 200 :
print(f’[{datetime.now().strftime(“%d-%b-%Y %H:%M:%S”)}] : Stopping the EC2 instances complete- {instance_id}’)
else:
print(f’[{datetime.now().strftime(“%d-%b-%Y %H:%M:%S”)}] : error in stopping ec2 instances’)
Note:
1. This script is developed for stopping an ec2 instance with a tag value.
2. To use the above script, create couple of instances with tag as stop_flag and assign the value as Yes. I already created one instance with the right tag.
3. The script extracts all instances which are having stop_flag as Yes and check the status of the instance. If the instance is in running state, the script will stop the instance.
Step -4: Create a test event to test the code before define the rule via event bridge. To test the code, click on the test tab and configure a test event.
Step -5: Click on the “Test” to test your code.
Step -6: You can see the execution results in the execution result tab
Step -7: To ensure, whether the code is able to stop the ec2 instance, go to ec2 console and verify the ec2 instance status
User can also verify the log details from lambda generated logs in cloud watch, to see the log, click on the Monitor (which is on the lambda function) and click on the View logs in cloud watch.
Well done. Lambda function for stop instance is working as expected and tested as well. Now we will define a rule and execute the lambda function from Event Bridge Rule (Schedule based)
Step -8: Search “Event Bridge” on the aws search and click on the event bridge and click on the create rule and provide the below details.
1. Give the rule name
2. Give some description about the rule.
3. Select the schedule option as we need to schedule to execute the rule and click next.
Step -9: Define the schedule pattern, this pattern is cron schedule, however ensure you select the local time zone for schedule to execute the rule.
Step -10: Select the target, here select AWS service and Lambda function and select your require lambda function.
Step-11: Select the Tags (it is optional) and finally the review and create rule page display, click create rule.
Step -12: User can see the new rule s enabled. Click the rule to see the next execution time.
Step -13: To ensure the ec2 instances are stopped by the rule, we created 2 instances with right tag ( stop_flag = Yes) and 2 instances are in running state
After the rule executed, the instances are stopped by the lambda function, user can also verify the lambda logs (from cloud watch logs) to ensure that the right instances are stopped.
Note — The same approach can be followed to start the ec2 instance :)