EC2 Management Made Easy: Create Your Own Auto-Shutdown Bash Script Today

EC2 Management Made Easy: Create Your Own Auto-Shutdown Bash Script Today

Overview

Managing EC2 instances can be a challenge, especially when it comes to controlling costs. One effective way to save money is by automatically shutting down instances when they’re not in use. In this blog post, we’ll walk you through creating a simple bash script that automatically shuts down your EC2 instances based on predefined conditions.

Prerequisites :-

Before we dive into the script creation process, make sure you have the following:

  • An AWS account with EC2 instances

  • AWS CLI installed and configured on your local machine

  • Basic knowledge of bash scripting

Procedure :-

Step 1: Create an ec2 instance

  • Login to the AWS management console and navigate to EC2 service

  • click on Launch Instance to create an ec2 instance.

  • Fill all the details and add the below script into your Ec2 user data

#!/bin/bash
# This script schedules an automatic shutdown for 21:30 UTC

# Check if any shutdowns are scheduled
shutdown_output=$(shutdown --show 2>&1)
if [[ $shutdown_output == *"No scheduled shutdown"* ]]; then
    echo "No shutdowns scheduled."
else
    echo "Cancelling scheduled shutdowns."
    shutdown -c
fi

# Schedule shutdown
shutdown_time="20:40"
shutdown $shutdown_time

# Create the systemd service file to ensure the shutdown is scheduled
cat <<EOF > /etc/systemd/system/auto-shutdown.service
[Unit]
Description=Schedules automatic shutdown for 21:30 UTC

[Service]
User=root
WorkingDirectory=/bin
ExecStart=/bin/sh -c "shutdown $shutdown_time"
Restart=on-failure
RestartSec=3
TimeoutSec=120

[Install]
WantedBy=multi-user.target
EOF

# Enable and start the service
systemctl enable auto-shutdown.service
systemctl start auto-shutdown.service
  • Finally launch the instance, the script will automatically shutdown the instance at the scheduled time.

Conclusion :-

Creating your own EC2 auto-shutdown script is a simple yet effective way to manage your AWS costs. By customizing the script to fit your specific needs, you can ensure that your EC2 instances are only running when necessary. Remember to regularly review and update your script as your needs change over time.