Check S3 Bucket Existence

  • ‘Cloud’
  • ‘Automation’ isCodeSnippet: true draft: false

Quick Tip

Don’t let your deployment blow up because of a missing S3 bucket. This Bash script lets you check if a bucket exists before anything fails clean and simple.

The Problem

Missing Bucket Failures

🔍 The Problem

If your CI/CD pipeline tries to upload files or sync data to an S3 bucket that doesn’t exist, things will break fast. You’ll waste time, pipeline minutes, and possibly miss something obvious. A quick pre-check could prevent all that.

Impact on Deployments

Failed deployments due to missing S3 buckets can waste valuable CI/CD time and delay releases.

The Solution

Bash Script Overview

The Fix

This script checks if an S3 bucket exists using the AWS CLI. It accepts --bucket or --b flags, gives color-coded logs, and adds a bit of fun to your terminal. Perfect for pre-checks in CI/CD jobs or local scripts.

Key Features

TL;DR

  • Use this script to check if an S3 bucket exists before your pipeline tries to use it.
  • Accepts --bucket or --b to pass the bucket name.
  • Includes clean logs, color output, and fun formatting for better readability.

Script Implementation

Color Definitions and Setup

check_bucket.sh
#!/usr/bin/env bash
# Color definitions
GREEN='\033[0;32m'
RED='\033[0;31m'
YELLOW='\033[1;33m'
CYAN='\033[0;36m'
NC='\033[0m' # No Color

ASCII Banner Function

Terminal window
#######################################
# Prints a fun ASCII banner header.
# Globals:
# CYAN
# NC
# Arguments:
# None
# Outputs:
# Writes header text to stdout.
#######################################
function print_fun() {
echo -e "${CYAN}"
echo "╭──────────────────────────────╮"
echo "│ ☁️ S3 Bucket Checker Bash │"
echo "╰──────────────────────────────╯"
echo -e "${NC}"
}

Logging Function

Terminal window
#######################################
# Prints a log message with timestamp and log level.
# Globals:
# CYAN, GREEN, RED, NC
# Arguments:
# $1 - Log level (INFO, SUCCESS, ERROR)
# $2 - Log message
# Outputs:
# Writes formatted log message to stdout.
#######################################
function log() {
local type="$1"
local message="$2"
local timestamp
timestamp=$(date "+%Y-%m-%d %H:%M:%S")
case "$type" in
INFO)
echo -e "${CYAN}[${timestamp}] [INFO]:${NC} $message"
;;
SUCCESS)
echo -e "${GREEN}[${timestamp}] [SUCCESS]:${NC} $message"
;;
ERROR)
echo -e "${RED}[${timestamp}] [ERROR]:${NC} $message"
;;
*)
echo -e "[${timestamp}] [LOG]: $message"
;;
esac
}

Initialization and Argument Parsing

Terminal window
#######################################
# Initializes script by parsing CLI arguments.
# Exits with error if bucket name is not provided.
# Globals:
# BUCKET_NAME, YELLOW, NC
# Arguments:
# --bucket | --b <bucket-name>
# Outputs:
# Sets BUCKET_NAME variable.
#######################################
function init() {
while [[ "$#" -gt 0 ]]; do
case "$1" in
--bucket|--b)
BUCKET_NAME="$2"
shift 2
;;
*)
log ERROR "Unknown argument: $1"
exit 1
;;
esac
done
if [[ -z "$BUCKET_NAME" ]]; then
log ERROR "Bucket name not provided. Use --bucket or --b to specify it."
echo -e "${YELLOW}Example:${NC} ./check_bucket.sh --bucket my-bucket-name"
exit 1
fi
}

Bucket Existence Check

Terminal window
#######################################
# Checks if the specified S3 bucket exists.
# Globals:
# BUCKET_NAME
# Outputs:
# Success or error message to stdout.
# Returns:
# 0 if bucket exists, exits with 1 otherwise.
#######################################
function check_bucket_exists() {
log INFO "Checking if bucket '$BUCKET_NAME' exists..."
if aws s3api head-bucket --bucket "$BUCKET_NAME" 2>/dev/null; then
log SUCCESS "Bucket '$BUCKET_NAME' exists and is accessible."
else
log ERROR "Bucket '$BUCKET_NAME' does not exist or access is denied."
exit 1
fi
}

Main Function

Terminal window
#######################################
# Main function that runs the script.
# Calls init and check_bucket_exists in order.
# Arguments:
# Passes all script arguments to init.
#######################################
function main() {
print_fun
init "$@"
check_bucket_exists
}
main "$@"

Usage and Benefits

Integration with CI/CD

Why This Helps

Adding this check to your CI/CD steps helps avoid silly failures and gives you faster feedback if something’s missing or misconfigured. It’s quick, readable, and reusable and you’ll thank yourself later.

Command Line Usage

Run the script with: ./check_bucket.sh --bucket my-bucket-name or ./check_bucket.sh --b my-bucket-name

Community Discussion

Your Approaches

Your Turn

How do you handle S3 checks in your automation? Got a trick or tool you use often? Let’s swap ideas.

Alternative Solutions

Share your favorite methods for validating S3 bucket existence in different environments.

Related Posts

Check out some of our other posts

List S3 Buckets

Overview Multi-Profile S3 Management Multi-Profile S3 Safari! Ever juggled multiple AWS accounts and needed a quick S3 bucket inventory across all of them? This Python script is your guid

AWS Secrets Manager

Need to load secrets in your Node.js app without exposing them? Here's how. If you're still storing API keys or database credentials in .env files or hardcoding them into your codebase, it's ti

Essential Bash Variables for Every Script

Overview Quick Tip You know what's worse than writing scripts? Writing scripts that break every time you move them to a different machine. Let's fix that with some built-in Bash variables tha

Why printf Beats echo in Linux Scripts

Scripting Tip You know that feeling when a script works perfectly on your machine but fails miserably somewhere else? That's probably because you're using echo for output. Let me show you why pri

Per-App Shell History for Bash

Terminal Chaos? Organize Your Bash History! Ever jumped between iTerm2, Ghostty, and VS Code's terminal only to have your command history get all mixed up? This Bash snippet keeps things clean by

Per-App Shell History for Zsh

Terminal Chaos? Organize Your Shell History! Ever jumped between iTerm2, Ghostty, and VS Code's terminal only to have your command history get all mixed up? This Zsh snippet keeps things clean by