Subscribe
AWS

Syncing many S3 buckets in parallel with a bash script

A small bash script that runs aws s3 sync for a list of buckets in parallel, keeps one log per bucket and tells you exactly which ones failed. Plus a dry run, a job limit and a count check afterwards.

Syncing many S3 buckets in parallel with a bash script

Earlier this year I needed a local copy of a set of S3 buckets. About thirty of them. All going to one machine, one folder per bucket.

aws s3 sync copies one bucket at a time. Running it thirty times in a row means every small bucket waits behind whatever big one came before it in the list. So I wrote a small bash script that starts one sync per bucket in the background, writes one log file per bucket and tells me at the end which ones failed.

Let us look at that script first, and then at the bits I'd add if I ran it again.

The first version

This is close to what I actually ran. The bucket names here are made up.

#!/usr/bin/env bash
set -euo pipefail

SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
LOG_DIR="$SCRIPT_DIR/logs"
mkdir -p "$LOG_DIR"

BUCKETS=(
  source-bucket-1
  source-bucket-2
  source-bucket-3
  example-app-content
  example-app-docs
)

PIDS=()
for BUCKET in "${BUCKETS[@]}"; do
  DEST="$SCRIPT_DIR/$BUCKET"
  mkdir -p "$DEST"
  (
    echo "[$(date '+%Y-%m-%d %H:%M:%S')] Starting sync: s3://${BUCKET} -> $DEST"
    aws s3 sync "s3://${BUCKET}" "$DEST"
    echo "[$(date '+%Y-%m-%d %H:%M:%S')] Finished sync: s3://${BUCKET}"
  ) > "$LOG_DIR/${BUCKET}.log" 2>&1 &
  PIDS+=($!)
  echo "  Spawned job for $BUCKET (pid $!)"
done

FAILED=()
for i in "${!BUCKETS[@]}"; do
  BUCKET="${BUCKETS[$i]}"
  if wait "${PIDS[$i]}"; then
    echo "  [OK]   $BUCKET"
  else
    echo "  [FAIL] $BUCKET  (see $LOG_DIR/${BUCKET}.log)"
    FAILED+=("$BUCKET")
  fi
done

if [[ ${#FAILED[@]} -eq 0 ]]; then
  echo "All ${#BUCKETS[@]} buckets synced successfully."
  exit 0
fi
echo "Sync failed for ${#FAILED[@]} bucket(s): ${FAILED[*]}"
exit 1

Each bucket goes into a folder with the same name next to the script. Bucket names are globally unique, so there's no chance of two of them landing in the same folder.

It uses whatever AWS credentials are default in the shell. Check that before you start, it's easy to be on the wrong profile.

aws sts get-caller-identity --query Arn --output text

How the parallel part works

The ( ... ) & runs each sync in a background subshell. $! is the PID of the job that was just started, and I keep them in an array in the same order as the bucket list. That way index i in PIDS belongs to index i in BUCKETS.

Then the second loop calls wait on each PID in order. wait <pid> returns the exit code of that job, even if it finished long before we got to it. Bash remembers it. So the loop doesn't care which bucket finishes first, it just collects the results.

The output while it runs is short. One line per bucket when it starts and one line per bucket at the end with OK or FAIL.

Why set -euo pipefail matters here

Three flags, and each one does something.

-e stops the script on the first command that fails. The subshell inherits it. So if aws s3 sync fails for a bucket, that subshell exits right there with the same exit code, the "Finished" line never gets written and wait sees the failure. Without -e the subshell would carry on, the echo at the end would succeed, and the exit code of the whole subshell would be 0. The bucket would show OK when it wasn't.

That one is easy to miss. The exit code of a subshell is the exit code of its last command.

-u turns an unset variable into an error. A typo like $BUCKTE would otherwise expand to nothing and you'd sync s3:// into the wrong place.

-o pipefail makes a pipeline fail if any part of it fails, not just the last part. There are no pipes in the first version. I add it anyway out of habit, and it matters the moment someone adds | tee to the sync line.

Notice the wait is inside an if. Commands in an if condition don't trigger -e, so one failed bucket doesn't kill the loop before the others are reported.

Reading the logs

Every bucket gets its own log in logs/. When something fails, the summary tells you which file to open. This was the best part of the script honestly. Thirty syncs writing to one terminal at the same time is unreadable.

Exit codes from aws s3 are worth knowing.

  • 0 means everything was copied.
  • 1 means at least one transfer failed. Permissions, a network error, a throttled request that ran out of retries.
  • 2 means some files were skipped but everything else went through. Objects in Glacier storage classes are a common reason, sync can't download those without a restore first.
  • 255 and nearby codes are for broken commands, missing credentials and similar.

The first version treats any non zero code as FAIL. That's fine, but it's nice to print the code too, so a 2 stands out from a 1 straight away.

What I'd change

Starting everything at once is fine for a one off run. It doesn't scale very well though. Each aws s3 sync already runs 10 concurrent requests by default, so thirty of them is three hundred connections. On a slow network that just makes everything slow together. A job limit fixes that.

I'd also move the bucket list into a file, add a dry run and print the exit code. Here is the second version. It works on the bash 3.2 that ships with macOS, which is why there's a read loop instead of mapfile.

#!/usr/bin/env bash
set -euo pipefail

SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
LIST_FILE="${1:-$SCRIPT_DIR/buckets.txt}"
DEST_ROOT="${DEST_ROOT:-$SCRIPT_DIR}"
LOG_DIR="$SCRIPT_DIR/logs"
MAX_JOBS="${MAX_JOBS:-8}"
DRY_RUN="${DRY_RUN:-0}"
mkdir -p "$LOG_DIR"

BUCKETS=()
while IFS= read -r line; do
  [[ -z "$line" || "$line" == \#* ]] && continue
  BUCKETS+=("$line")
done < "$LIST_FILE"

if [[ "$DRY_RUN" == 1 ]]; then
  FLAGS=(--dryrun)
else
  FLAGS=(--only-show-errors)
fi

sync_one() {
  local bucket="$1"
  local dest="$DEST_ROOT/$bucket"
  mkdir -p "$dest"
  echo "[$(date '+%F %T')] start s3://$bucket -> $dest"
  aws s3 sync "s3://$bucket" "$dest" "${FLAGS[@]}"
  echo "[$(date '+%F %T')] done s3://$bucket"
}

PIDS=()
for bucket in "${BUCKETS[@]}"; do
  while [[ $(jobs -rp | wc -l) -ge $MAX_JOBS ]]; do
    sleep 1
  done
  sync_one "$bucket" > "$LOG_DIR/$bucket.log" 2>&1 &
  PIDS+=($!)
  echo "started $bucket (pid $!)"
done

FAILED=()
for i in "${!BUCKETS[@]}"; do
  bucket="${BUCKETS[$i]}"
  rc=0
  wait "${PIDS[$i]}" || rc=$?
  if [[ $rc -eq 0 ]]; then
    echo "  [OK]   $bucket"
  else
    echo "  [FAIL] $bucket (exit $rc, see $LOG_DIR/$bucket.log)"
    FAILED+=("$bucket")
  fi
done

if [[ ${#FAILED[@]} -gt 0 ]]; then
  echo "${#FAILED[@]} of ${#BUCKETS[@]} buckets failed: ${FAILED[*]}"
  exit 1
fi
echo "All ${#BUCKETS[@]} buckets synced."

The list file is one bucket per line. Blank lines and lines starting with # are skipped.

# buckets to copy
source-bucket-1
source-bucket-2
source-bucket-3

jobs -rp lists the PIDs of background jobs that are still running. The inner while just sleeps until there's a free slot. It's crude, but it works on old bash and there's nothing to install.

--only-show-errors keeps the logs small on a real run. A normal sync prints one line per file and with a bucket of a few hundred thousand objects the log gets huge. On a dry run I want the opposite, every line, so the flags swap.

|| rc=$? is how you get the exit code without -e stopping the script. The rc=0 before it matters, otherwise rc keeps the value from the previous bucket.

Running it looks like this.

DRY_RUN=1 ./sync_buckets.sh buckets.txt
grep -c dryrun logs/source-bucket-1.log
MAX_JOBS=4 ./sync_buckets.sh buckets.txt

The grep -c gives a rough idea of how many files each bucket will copy before you spend the bandwidth.

Checking the counts afterwards

An exit code of 0 tells you sync didn't hit an error. It doesn't tell you the copy is complete. So after a run I'd compare object counts.

#!/usr/bin/env bash
set -euo pipefail

LIST_FILE="${1:-buckets.txt}"
DEST_ROOT="${DEST_ROOT:-.}"

while IFS= read -r bucket; do
  [[ -z "$bucket" || "$bucket" == \#* ]] && continue
  remote=$(aws s3 ls "s3://$bucket" --recursive --summarize \
    | awk '/Total Objects:/ {print $3}')
  local_count=$(find "$DEST_ROOT/$bucket" -type f | wc -l | tr -d ' ')
  if [[ "$remote" == "$local_count" ]]; then
    status=OK
  else
    status=DIFF
  fi
  printf '%-6s %-40s remote=%-8s local=%s\n' "$status" "$bucket" "$remote" "$local_count"
done < "$LIST_FILE"

A DIFF doesn't always mean something went wrong. The S3 console creates empty "folder" objects with keys ending in /, and those count as objects but don't become files. A key like a and another key like a/b can't both exist on a local disk either, sync warns and skips one. For those, open the log and look for warning: lines.

The same script works for bucket to bucket copies too. Swap the local folder for s3://target-bucket/$bucket in sync_one and drop the find check for a second aws s3 ls on the target. Just remember the credentials need read on the source and write on the target.