Start/stop Upgrade/downgrade EC2 instances with lambda functions

pratikcodes

Pratik Tiwari

Posted on August 15, 2021

Start/stop Upgrade/downgrade EC2 instances with lambda functions

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.
  3. 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))

Upgrade/downgrade(modify)

import boto3
ec2 = boto3.client('ec2')
instance_id = 'i-05ca5f05f965b3a4b'
ec2.stop_instances(InstanceIds=[instance_id])
waiter=ec2.get_waiter('instance_stopped')
waiter.wait(InstanceIds=[instance_id])
ec2.modify_instance_attribute(InstanceId=instance_id, Attribute='instanceType', Value='t2.small')
ec2.start_instances(InstanceIds=[instance_id])
print("instances modified and started")

Reference

Official AWS documentation:
https://aws.amazon.com/premiumsupport/knowledge-center/start-stop-lambda-cloudwatch/
Video explanation:
https://www.youtube.com/watch?v=oISuE16pGFQ

💖 💪 🙅 🚩
pratikcodes
Pratik Tiwari

Posted on August 15, 2021

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related