How to Write an AWS CLI Script to Automate Common Cloud Tasks

How to Use an AWS CLI to Automate Common Cloud Tasks

Posted by:

|

On:

|

In today’s cloud-driven world, automation is key to efficiency, scalability, and cost savings. The AWS Command Line Interface (CLI) allows developers and system administrators to automate common tasks without relying on the AWS Management Console. In this guide, we’ll walk you through writing an AWS CLI script to automate frequent cloud operations. (How to Automate Cloud Deployments Using AWS CLI and SDKs)

Why Use AWS CLI for Automation?

AWS CLI is a powerful tool that lets you interact with AWS services via terminal commands. With scripting, you can:
✅ Automate repetitive tasks (e.g., starting/stopping instances)
✅ Reduce human errors
✅ Improve efficiency and deployment speed
✅ Save costs by controlling resource usage

Prerequisites

Before you begin, make sure you have the following:

  • AWS CLI installed – Download AWS CLI
  • AWS credentials configured (aws configure)
  • Basic knowledge of Bash or Python scripting

Step 1: Define Your Automation Goals

The first step is to identify the tasks you want to automate. Some common AWS tasks include:

  • Starting and stopping EC2 instances
  • Creating and managing S3 buckets
  • Automating backups using snapshots
  • Deploying applications with Lambda

For this tutorial, let’s automate the process of starting and stopping EC2 instances.

Step 2: Writing a Basic AWS CLI Script

We’ll create a Bash script to:

  1. List running EC2 instances
  2. Stop instances when not in use
  3. Start instances when needed

Listing Running EC2 Instances

To check running instances, use:

aws ec2 describe-instances --filters "Name=instance-state-name,Values=running" \
--query "Reservations[*].Instances[*].InstanceId" --output text

Stopping EC2 Instances

Now, let’s create a script to stop instances automatically.

#!/bin/bash

# Fetch running instances
INSTANCES=$(aws ec2 describe-instances --filters "Name=instance-state-name,Values=running" \
--query "Reservations[*].Instances[*].InstanceId" --output text)

# Stop instances if there are any running
if [ -z "$INSTANCES" ]; then
echo "No running instances found."
else
echo "Stopping instances: $INSTANCES"
aws ec2 stop-instances --instance-ids $INSTANCES
fi

Save this script as stop-instances.sh, then run:

chmod +x stop-instances.sh  
./stop-instances.sh

Starting EC2 Instances

To start stopped instances, modify the script:

#!/bin/bash

# Fetch stopped instances
INSTANCES=$(aws ec2 describe-instances --filters "Name=instance-state-name,Values=stopped" \
--query "Reservations[*].Instances[*].InstanceId" --output text)

# Start instances if any are stopped
if [ -z "$INSTANCES" ]; then
echo "No stopped instances found."
else
echo "Starting instances: $INSTANCES"
aws ec2 start-instances --instance-ids $INSTANCES
fi

Save it as start-instances.sh and execute it the same way.

Step 3: Automate with a Cron Job

To make this fully automated, add it to a cron job (Linux/macOS) or Task Scheduler (Windows).

For Linux/macOS, run:

crontab -e

Add this line to stop instances at 10 PM every day:

0 22 * * * /path/to/stop-instances.sh

Modify accordingly for starting instances in the morning.

Step 4: Enhancing Your Script

To make it more robust, consider:
✅ Logging actions to track automation history
✅ Sending notifications (via AWS SNS or email)
✅ Adding error handling to catch AWS API failures

Here’s an improved version with logging:

#!/bin/bash
LOG_FILE="/var/log/aws-instance-manager.log"
echo "$(date): Checking for running instances..." >> $LOG_FILE

INSTANCES=$(aws ec2 describe-instances --filters "Name=instance-state-name,Values=running" \
--query "Reservations[*].Instances[*].InstanceId" --output text)

if [ -z "$INSTANCES" ]; then
echo "$(date): No running instances found." >> $LOG_FILE
else
echo "$(date): Stopping instances: $INSTANCES" >> $LOG_FILE
aws ec2 stop-instances --instance-ids $INSTANCES
fi

Final Thoughts

Automating AWS tasks with CLI scripts saves time, reduces manual effort, and ensures resources are efficiently managed. Whether it’s EC2 management, S3 backups, or database maintenance, AWS CLI scripting can streamline your cloud operations.

🚀 Next Steps: Try extending this script for other AWS services like RDS, S3, Lambda, or integrate it with a CI/CD pipeline for full automation!

Let me know if you need more advanced automation ideas! 🚀

Latest Posts

Leave a Reply

Your email address will not be published. Required fields are marked *