Start/stop Upgrade/downgrade EC2 instances with lambda functions

Pratik Tiwari
2 min readAug 15, 2021

Lambda functions are one of the most common services by AWS that comes really in handy. One of the very useful applications is the automation of starting/stopping and upgrading these instances.

Example.

You want to start instances for a failover you can use the start and stop instances using lambda function by triggering the function use cloud watch alarm.

You want to scale up (vertically) an instance when it has a CPU utilization of more than some amount or has more traffic.

If you want to start and stop a dev instance in the night and you want to automate this process you can use a cloud watch event with a corn job to this.

It has more and endless application

Enough of all talk let’s get into it.

  1. Create an IAM role with a policy that has full access for lambda. (IMPORTANT)
  2. After Role is created create a lambda function with python 3.8 and use the role that you created above.

Use this code for the lambda function:

Start Instances :

import boto3
region = 'us-west-1'
instances = ['i-12345cb6de4f78g9h', 'i-08ce9b2d7eccf6d26']
ec2 = boto3.client('ec2', region_name=region)
def lambda_handler(event, context):
ec2.stop_instances(InstanceIds=instances)
print('stopped your instances: ' + str(instances))

Stop Instances:

import boto3
region = 'us-west-1'
instances = ['i-12345cb6de4f78g9h', 'i-08ce9b2d7eccf6d26']
ec2 = boto3.client('ec2', region_name=region)
def lambda_handler(event, context):
ec2.start_instances(InstanceIds=instances)
print('started your instances: ' + str(instances))

Change (upgrade/downgrade) Instances:

import boto3
ec2 = boto3.client('ec2')
# choose an EC2 instance with id
instance_id = 'i-05ca5f05f965b3a4b'
# Stop the instance
ec2.stop_instances(InstanceIds=[instance_id])
waiter=ec2.get_waiter('instance_stopped')
waiter.wait(InstanceIds=[instance_id])
# Change the instance type
ec2.modify_instance_attribute(InstanceId=instance_id, Attribute='instanceType', Value='t2.small')
# Start the instance
ec2.start_instances(InstanceIds=[instance_id])
print("instances modified and started")

--

--

Pratik Tiwari

fullstack dev at a bay area startup ✶ Incosistent open source contributor ✶ Go ✶ JS ✶ web3 🌐