Learn how to efficiently start and stop EC2 instances using three powerful AWS tools: AWS CLI, Boto3 (Python SDK), and AWS Lambda. This step-by-step guide is perfect for developers, DevOps professionals, and cloud enthusiasts looking to automate EC2 instance management and reduce costs.
In this video, you'll learn:
How to use the AWS CLI to start and stop EC2 instances.
Writing Python scripts with Boto3 for EC2 automation.
Creating an AWS Lambda function to manage EC2 instances.
Automate (schedule) start/stop ec2 instance by lambda
Best practices for automating EC2 management to save time and resources.
This tutorial is beginner-friendly and packed with practical examples to help you get started quickly.
ec2-start.sh
-------------------
Replace INSTANCE_ID with your EC2 instance ID
INSTANCE_ID="i-0abcd1234efgh5678"
Start EC2 Instance
aws ec2 start-instances --instance-ids $INSTANCE_ID
echo "Instance $INSTANCE_ID is starting..."
ec2-stop.sh
------------------
Replace INSTANCE_ID with your EC2 instance ID
INSTANCE_ID="i-0abcd1234efgh5678"
Stop EC2 Instance
aws ec2 stop-instances --instance-ids $INSTANCE_ID
echo "Instance $INSTANCE_ID is stopping..."
ec2-start.py
---------------------
import boto3
def start_instance(instance_id):
ec2 = boto3.client('ec2')
response = ec2.start_instances(InstanceIds=[instance_id])
print(f"Starting instance {instance_id}: {response}")
start_instance('i-0abcd1234efgh5678')
ec2-stop.py
------------------
import boto3
def stop_instance(instance_id):
ec2 = boto3.client('ec2')
response = ec2.stop_instances(InstanceIds=[instance_id])
print(f"Stopping instance {instance_id}: {response}")
stop_instance('i-0abcd1234efgh5678')
lambda function file
-------------------------------
import boto3
import os
def lambda_handler(event, context):
EC2 instance ID to start (replace with your instance ID or pass via event)
instance_id = event.get("instance_id", "i-0abcd1234efgh5678")
Initialize EC2 client
ec2 = boto3.client('ec2')
try:
Start the EC2 instance
response = ec2.start_instances(InstanceIds=[instance_id])
return {
"statusCode": 200,
"body": f"Successfully started instance {instance_id}",
"response": response
}
except Exception as e:
return {
"statusCode": 500,
"body": f"Error starting instance {instance_id}: {str(e)}"
}
====================
Don't forget to: ✅ Like this video if you found it helpful.
✅ Subscribe for more AWS and DevOps tutorials.
✅ Drop a comment with your questions or suggestions for future videos!
#AWS #EC2 #Automation #Boto3 #Lambda #AWSCLI #DevOps #CloudComputing