Using Python Boto3 and Lambda functions to start/stop EC2 Instances Based on Tags

In this blog we have to create script to start/stop ec2 instances using python script based on tags, to launch instances check here.

  • An AWS Account with An IAM User with IAM, Lambda, EC2 Access

Let’s name role name as lambda-ec2-access, above policy gives access to instances which contains auto-start-stop: Yes tags.

Launch instances and add tags, if instances already exists just add auto-start-stop: Yes tags to instances.

stop-ec2-instances

  • Goto Lambda console and click on create function
  • Create lambda functions with stop-ec2-instance, python3.8 runtime, and lambda-ec2-access role.
  • Goto code editor and start writing the code.
  • import boto3 and json modules.
import json
import boto3
  • Lets invoke resource for EC2 along with the region name where we are going to perform this activity.
ec2 = boto3.resource('ec2', region_name='ap-south-1')
  • First search for instance which are in running state and are having auto-start-stop tag as “Yes” by using instances.filter(). Checkout he official documentation for this method here
def lambda_handler(event, context):
instances = ec2.instances.filter(Filters=[{'Name': 'instance-state-name', 'Values': ['running']},{'Name': 'tag:auto-start-stop','Values':['Yes']}])
  • List returned using for loop and fetch instance ids and save it in variable id.
def lambda_handler(event, context):
instances = ec2.instances.filter(Filters=[{'Name': 'instance-state-name', 'Values': ['running']},{'Name': 'tag:auto-start-stop','Values':['Yes']}])
for instance in instances:
id=instance.id
  • Stopping instances given a list of instance IDs filtering. This will stop all running instances having auto-start-stop tag with value as Yes.
def lambda_handler(event, context):
instances = ec2.instances.filter(Filters=[{'Name': 'instance-state-name', 'Values': ['running']},{'Name': 'tag:Env','Values':['Dev']}])
for instance in instances:
id=instance.id
ec2.instances.filter(InstanceIds=[id]).stop()
print("Instance ID is stopped:- "+instance.id)
return "success"

To view entire stop-ec2-instances code

start-ec2-instances

  • Goto Lambda console and click on create function
  • Create lambda functions with start-ec2-instance, python3.8 runtime, and lambda-ec2-access role.
  • Goto code editor and start writing the code.
  • import boto3 and json modules.
import json
import boto3
  • Lets invoke resource for EC2 along with the region name where we are going to perform this activity.
ec2 = boto3.resource('ec2', region_name='ap-south-1')
  • First search for instance which are in stopped state and are having auto-start-stop tag as “Yes” by using instances.filter(). Checkout he official documentation for this method here
def lambda_handler(event, context):
instances = ec2.instances.filter(Filters=[{'Name': 'instance-state-name', 'Values': ['stopped']},{'Name': 'tag:auto-start-stop','Values':['Yes']}])
  • List returned using for loop and fetch instance ids and save it in variable id.
def lambda_handler(event, context):
instances = ec2.instances.filter(Filters=[{'Name': 'instance-state-name', 'Values': ['stopped']},{'Name': 'tag:auto-start-stop','Values':['Yes']}])
for instance in instances:
id=instance.id
  • Stopping instances given a list of instance IDs filtering. This will start all stopped instances having auto-start-stop tag with value as Yes.
def lambda_handler(event, context):
instances = ec2.instances.filter(Filters=[{'Name': 'instance-state-name', 'Values': ['stopped']},{'Name': 'tag:Env','Values':['Dev']}])
for instance in instances:
id=instance.id
ec2.instances.filter(InstanceIds=[id]).stop()
print("Instance ID is stopped:- "+instance.id)
return "success"

To view entire start-ec2-instances code

Once lambda functions created trigger them, it will start or stop instances based on instance state. Or can take this setup up cron jobs to run on specific time using Eventbridge, Jenkins, crontab etc.

  • Terminate EC2 instances
  • Delete Lambda functions for start and stop
  • Delete Lambda Role

Boto3 provided inbuild methods for AWS resources using which many task can be automated by writing a python script.

Stay tuned for my next blog…..

So, did you find my content helpful? If you did or like my other contents? Follow me for more blogs

Thanks for Reading !!

Keep Learning !! Keep Sharing !!

You can contact me on:

LinkedIn emailme

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Vinodha kumara

DevSecOps, MLOps, Cloud Computing, DE, ML, DL, Programmer, Blogger, Volunteer