AWS EC2 instance schedule start stop
Managing the start and stop states of AWS EC2 instances is a crucial task for optimizing costs and maintaining a scalable infrastructure. Automating this process can save significant time and prevent unnecessary expenses by ensuring that resources are only running when needed. This comprehensive guide will explore various methods to automate the start and stop of AWS EC2 instances, including Bash scripts, Python scripts with Boto3, AWS CLI, Lambda functions, and AWS EventBridge (formerly CloudWatch Events).
Key Topics Covered
- Understanding EC2 Instance Lifecycle
- Prerequisites for Automation
- Using Bash Scripts with AWS CLI
- Using Python Scripts with Boto3
- Using AWS Lambda with EventBridge
- Advanced Scheduling with AWS Systems Manager
- Best Practices for Automation
- Conclusion
1. Understanding EC2 Instance Lifecycle
AWS EC2 instances can exist in various states, including:
- Running: The instance is operational and incurring charges.
- Stopped: The instance is not running but retains its data (minimal charges for EBS volumes).
- Terminated: The instance is permanently deleted.
Automating transitions between these states helps manage costs and ensures resources are used efficiently.
2. Prerequisites for Automation
- AWS CLI Installed and Configured:
- Install AWS CLI:
sudo apt install awscli -y # For Ubuntu - Configure the CLI with appropriate credentials:
aws configure
- Install AWS CLI:
- IAM Role/Policy:
- Grant permissions to start, stop, describe EC2 instances:
{ "Version": "2012-10-17", "Statement": [ { "Effect": "Allow", "Action": [ "ec2:StartInstances", "ec2:StopInstances", "ec2:DescribeInstances" ], "Resource": "arn:aws:ec2:*:*:instance/*" } ] }
- Grant permissions to start, stop, describe EC2 instances:
- Identify Instance IDs:
- List instance IDs:
aws ec2 describe-instances --query "Reservations[*].Instances[*].InstanceId" --output text
- List instance IDs:
AWS EC2 instance schedule start stop
3. Using Bash Scripts with AWS CLI
Script: start_stop_ec2.sh
#!/bin/bash
# AWS EC2 Instance Automation Script
# Author: [Your Name]
# Version: 1.0
# Configuration
INSTANCE_IDS="i-0123456789abcdef0 i-0abcdef1234567890" # Space-separated instance IDs
REGION="us-east-1" # AWS region
ACTION=$1 # Action: start or stop
# Log file
LOG_FILE="/var/log/aws_ec2_start_stop.log"
# Function to log messages
log_message() {
echo "[$(date '+%Y-%m-%d %H:%M:%S')] $1" | tee -a "$LOG_FILE"
}
# Function to validate action
validate_action() {
if [[ "$ACTION" != "start" && "$ACTION" != "stop" ]]; then
log_message "Invalid action: $ACTION. Use 'start' or 'stop'."
exit 1
fi
}
# Perform the action
perform_action() {
log_message "Performing '$ACTION' on instances: $INSTANCE_IDS..."
if [[ "$ACTION" == "start" ]]; then
aws ec2 start-instances --instance-ids $INSTANCE_IDS --region $REGION
elif [[ "$ACTION" == "stop" ]]; then
aws ec2 stop-instances --instance-ids $INSTANCE_IDS --region $REGION
fi
if [[ $? -eq 0 ]]; then
log_message "Action '$ACTION' completed successfully."
else
log_message "Action '$ACTION' failed."
exit 1
fi
}
# Main script execution
validate_action
perform_action
Usage
- Save the Script: Save the script as
start_stop_ec2.shand make it executable:chmod +x start_stop_ec2.sh - Run the Script:
- Start instances:
./start_stop_ec2.sh start - Stop instances:
./start_stop_ec2.sh stop
- Start instances:
- Automate with
cron: Schedule periodic actions:crontab -eAdd:
0 9 * * * /path/to/start_stop_ec2.sh start >> /var/log/cron.log 2>&1 0 18 * * * /path/to/start_stop_ec2.sh stop >> /var/log/cron.log 2>&1
4.start and stop aws ec2 instance using python boto3
Script: start_stop_ec2.py
import boto3
import sys
import logging
# Configuration
INSTANCE_IDS = ["i-0123456789abcdef0", "i-0abcdef1234567890"] # Instance IDs
REGION = "us-east-1" # AWS region
ACTION = sys.argv[1] if len(sys.argv) > 1 else None # Action: start or stop
LOG_FILE = "/var/log/aws_ec2_start_stop.log"
# Logging setup
logging.basicConfig(filename=LOG_FILE, level=logging.INFO, format="%(asctime)s - %(message)s")
def log_message(message):
logging.info(message)
print(message)
# Validate action
if ACTION not in ["start", "stop"]:
log_message("Invalid action. Use 'start' or 'stop'.")
sys.exit(1)
# Perform action
ec2 = boto3.client("ec2", region_name=REGION)
try:
if ACTION == "start":
log_message(f"Starting instances: {INSTANCE_IDS}")
ec2.start_instances(InstanceIds=INSTANCE_IDS)
elif ACTION == "stop":
log_message(f"Stopping instances: {INSTANCE_IDS}")
ec2.stop_instances(InstanceIds=INSTANCE_IDS)
log_message(f"Action '{ACTION}' completed successfully.")
except Exception as e:
log_message(f"Error during '{ACTION}': {e}")
sys.exit(1)
Usage
- Install Boto3:
pip install boto3 - Run the Script:
- Start instances:
python3 start_stop_ec2.py start - Stop instances:
python3 start_stop_ec2.py stop
- Start instances:
5. Using AWS Lambda with EventBridge
Lambda Function
- Python Code:
import boto3 def lambda_handler(event, context): ec2 = boto3.client("ec2", region_name="us-east-1") action = event.get("action") # 'start' or 'stop' instance_ids = ["i-0123456789abcdef0", "i-0abcdef1234567890"] if action == "start": ec2.start_instances(InstanceIds=instance_ids) return f"Started instances: {instance_ids}" elif action == "stop": ec2.stop_instances(InstanceIds=instance_ids) return f"Stopped instances: {instance_ids}" else: return "Invalid action" - Deploy the Function:
- Create a Lambda function using the code above.
- Assign a role with
ec2:StartInstances,ec2:StopInstances, andec2:DescribeInstancespermissions.
EventBridge Rule
- Create a Rule:
- Go to EventBridge > Rules > Create Rule.
- Define a schedule (e.g., stop instances at 6 PM).
- Target:
- Set the Lambda function as the target.
- Pass
{"action": "start"}or{"action": "stop"}as input.
6. Advanced Scheduling with AWS Systems Manager
AWS Systems Manager (SSM) allows you to run commands on instances.
- Create an SSM Document:
- Use the document
AWS-StartEC2InstanceorAWS-StopEC2Instance.
- Use the document
- Schedule an Automation:
- Go to SSM Automation and create a scheduled run.
7. Best Practices for Automation
- Use Tags:
- Tag instances (e.g.,
Environment: Dev) and filter them dynamically. - Example with CLI:
aws ec2 describe-instances --filters "Name=tag:Environment,Values=Dev" --query "Reservations[*].Instances[*].InstanceId"
- Tag instances (e.g.,
- Monitor with CloudWatch:
- Set up alarms to verify instance state changes.
- Secure IAM Permissions:
- Use least-privilege IAM roles.
- Test Before Automating:
- Test scripts on a small subset of instances.
Reference
Conclusion
Automating the start and stop of AWS EC2 instances can save costs, improve efficiency, and reduce manual workload. This guide provided multiple approaches, including Bash scripts, Python with Boto3, AWS Lambda, and EventBridge. By choosing the right method for your infrastructure, you can streamline your operations and ensure resources are managed effectively.
