Write a Bash script that deploys to a list of servers one by one and stops on the first failure (a rolling deploy).
AdvancedHands-onBash scripting tasks
Answer
#!/usr/bin/env bash
set -euo pipefail
VERSION="${1:?version required}"
mapfile -t HOSTS < hosts.txt
for h in "${HOSTS[@]}"; do
echo "==> $h: draining"
ssh -n "$h" "sudo /opt/lb/deregister.sh"
echo "==> $h: deploying $VERSION"
ssh -n "$h" "sudo /opt/app/deploy.sh $VERSION"
for i in {1..30}; do
if ssh -n "$h" "curl -sf localhost:8080/health" >/dev/null; then break; fi
if (( i == 30 )); then echo "$h failed health check, aborting rollout" >&2; exit 1; fi
sleep 2
done
ssh -n "$h" "sudo /opt/lb/register.sh"
echo "==> $h: OK"
done
Key trick → set -e plus an explicit health gate per host means a bad version is stopped after one server, never all of them. mapfile reads the host list safely into an array.
More on Bash scripting tasks
Write the safe header you start every Bash script with, and explain each part.BeginnerWrite a script that alerts when any filesystem is above 80% usage.BeginnerParse an Nginx access log and print the top 10 client IPs by request count.BeginnerWrite a backup script that tars a directory with a timestamp and keeps only the last 7 backups.IntermediateWrite a health-check loop that polls a URL until it returns 200, with a timeout.IntermediateParse command-line flags `-e <env>`, `-v` (verbose) and `-h` in a Bash script.Intermediate