AWS Lambda function to start and stop EC2 instances with Terraform code

AWS Lambda function to start and stop EC2 instances with Terraform code

Lambda function written in Python which when triggered starts or stops the EC2 instances.

start_ec2_instances.py

import boto3

ec2 = boto3.resource('ec2', 'us-east-1')

def lambda_handler(event, context):
 instances = ec2.instances.filter(Filters=[{'Name': 'instance-state-name', 'Values': ['stopped']},{'Name': 'tag:AutoStop','Values':['true']}])
 for instance in instances:
     id=instance.id
     ec2.instances.filter(InstanceIds=[id]).start()
     print("Instance ID is started:- "+instance.id)
 return "success"

stop_ec2_instances.py

import boto3

ec2 = boto3.resource('ec2', 'us-east-1')

def lambda_handler(event, context):
 instances = ec2.instances.filter(Filters=[{'Name': 'instance-state-name', 'Values': ['running']},{'Name': 'tag:AutoStop','Values':['true']}])
 for instance in instances:
     id=instance.id
     ec2.instances.filter(InstanceIds=[id]).stop()
     print("Instance ID is stopped:- "+instance.id)
 return "success"

NOTE: All the EC2 instances which you need to start or stop must contain the tag AutoStop = true

To view the complete terraform code, click here.