Using the lambda function with python code, we will be able to shut down the EC2-instances automatically. The python code that can be executed automatically using the aws cloudwatch rules has been provided below.
To save costs on AWS EC2, it may be necessary in some cases to automatically shut down EC2 instances during off-peak hours. For example, if the developers have a few EC2 instances running, we can automatically shut them down during their non-working hours using lambda functions and cloudwatch rules.
- AWS Lambda
- AWS Cloudwatch
The python codes added below will stop and start all ec2-instances every day at 12:15 AM GMT and 08:15 AM GMT respectively with instance tags key: "env" and value: "testing"
The python code has been written below::
import boto3
REGION = "ap-south-1"
def lambda_handler(event, context):
ec2 = boto3.client('ec2',region_name=REGION)
all_ec2 = ec2.describe_instances(
Filters=[
{'Name':'tag:env', 'Values':["testing"]}
]
)
for instance in all_ec2['Reservations'][0]['Instances']:
print("Stopping Ec2 : {} ".format( instance['InstanceId'] ))
ec2.stop_instances(InstanceIds=[ instance['InstanceId'] ])
import boto3
REGION = "ap-south-1"
def lambda_handler(event, context):
ec2 = boto3.client('ec2',region_name=REGION)
all_ec2 = ec2.describe_instances(
Filters=[
{'Name':'tag:env', 'Values':["testing"]}
]
)
for instance in all_ec2['Reservations'][0]['Instances']:
print("Starting Ec2 : {} ".format( instance['InstanceId'] ))
ec2.start_instances(InstanceIds=[ instance['InstanceId'] ])
The Cloudwatch rules will execute the python codes added in the Lambda functions and it will stop and start all ec2-instances every day at 12:15 AM GMT and 08:15 AM GMT respectively with the instance tags key: "env" and value: "testing"
Created by @sebinxavi - feel free to contact me and advise as necessary!