Frame: in the terminal
curl -s …/healthz; echo $? output a 500 error page and 0; the frame flashes red.Narration: curl returns zero, which only means “the transfer succeeded”, not “the request succeeded”.
--fail-with-body,-w '%{http_code}'), set connect / total timeouts, retry correctly with exponential backoff (including Retry-After), and paginate by Link header.--query (JMESPath),-o tsv / --output text and jq division of labor, avoiding pitfalls with pagers, colors, interactive prompts and locale defaults (all read-only, zero-cost examples; cloud parts optional).xargs -P, GNU parallel,ssh -n -o BatchMode=yes loops, collecting the exit code and output of each host.releases/<timestamp> + current symlink, atomic switchover (rename(2)), health-check failure triggers automatic rollback, and old releases are cleaned up.flock guard against concurrent runs.health <url>,backup <dir> and deploy as three subcommands (lib/cmd_health.sh , etc.).| # | Time | Module | Core content | Animation / interaction | Lab |
|---|---|---|---|---|---|
| 0 | Before class | Preparation: cloud account (optional) and API sandbox | Start the local mock API (mockapi.py) and confirm opsctl is at the Lesson 4 v0.2.0, optionally sign in to az / aws | Environment self-check checklist | Start the sandbox and self-check |
| 1 | 00–06 | Calling HTTP APIs: curl, status codes, retries and pagination | -f / --fail-with-body,-w, timeouts,--retry family,Retry-After,Link pagination,--json | Core animation (part 1): API calls with retries and backoff | Retries and pagination against the mock API |
| 2 | 06–13 | Scripting cloud CLIs: --query, --output and jq for az and aws | JMESPath,-o tsv / --output text,jq -r, pagers and auto-pagination, errors and exit codes | Interactive demo: “same JSON, three ways to query it” | Offline JSON exercise + optional read-only cloud queries |
| 3 | 13–21 | Bulk operations: parallel execution and SSH loops | xargs -P, GNU parallel (--joblog,--tag), SSH loop’s -n,BatchMode options ConnectTimeout | Concurrency timeline simulator | Check the hosts in servers.csv in parallel |
| 4 | 21–28 | Deploy scripts: health checks, rollback and atomic switchover | releases/ + current symlink,ln -sfn + mv -T, health checks, auto-rollback, cleanup | Core animation (part 2): atomic switchover and rollback | Deploy 3 versions locally and trigger a rollback |
| 5 | 28–35 | Backup and rotation scripts | tar + timestamp, temp file + atomic rename, sha256, rotation by count / age, flock, restore drill | Rotation window visualization | Back up ~/bashlab/data and verify the restore |
| 6 | 35–42 | Scheduled runs: cron and systemd timers | crontab syntax and environment pitfalls,OnCalendar,Persistent,RandomizedDelaySec, user-level timers | cron vs. timer comparison timeline | Run backups with a user-level systemd timer |
| 7 | 42–50 | Running scripts in CI: GitHub Actions / GitLab CI | Bash defaults in CI, secrets and masking, exit codes, artifacts, OIDC cloud login (see the CI course) | CI job execution flow | Write a CI job for opsctl |
| 8 | 50–60 | opsctl v0.3: health, backup and deploy | Full code for the three subcommands, dispatch, exit codes, config options and troubleshooting tree | opsctl execution path + interactive troubleshooting tree | Finish v0.3 and self-test |
| — | After class | Cheat sheet · Capstone lab | “From API to deploy” end-to-end script | Final quiz (12 questions) | Capstone lab |
| Target skills | M1 | M2 | M3 | M4 | M5 | M6 | M7 | M8 | Key commands / objects | Lab |
|---|---|---|---|---|---|---|---|---|---|---|
| HTTP status codes and curl exit codes | ✓ | · | ✓ | ✓ | · | · | ✓ | ✓ | --fail-with-body,-w '%{http_code}', rc 22 / 28 / 7 | M1 |
| Retries, backoff and timeouts | ✓ | · | ✓ | ✓ | · | · | · | ✓ | --retry,--max-time,util::retry | M1 / M8 |
| JSON processing and cloud CLIs | ✓ | ✓ | · | · | · | · | ✓ | · | --query,-o tsv,jq -r | M2 |
| Parallelism and bulk SSH | · | · | ✓ | · | · | · | · | · | xargs -0 -P,parallel --joblog,ssh -n -o BatchMode=yes | M3 |
| Atomic switchover and rollback | · | · | · | ✓ | ✓ | · | · | ✓ | ln -sfn,mv -T,readlink | M4 |
| Backup, verification and rotation | · | · | · | · | ✓ | ✓ | · | ✓ | tar,sha256sum -c,find -print0 | sort -z | M5 |
| Concurrency protection | · | · | · | ✓ | ✓ | ✓ | · | ✓ | flock -n,mktemp,trap | M5 / M6 |
| Scheduled runs | · | · | · | · | · | ✓ | · | · | crontab -e,OnCalendar=,systemctl --user list-timers | M6 |
| Running scripts in CI | · | ✓ | · | · | · | · | ✓ | ✓ | shell: bash,::add-mask::,.gitlab-ci.yml | M7 |
| Topic | Why it is not in this lesson | Where to learn it |
|---|---|---|
| Creating cloud resources, networking and permission design (VMs, VNets, IAM, RBAC) | This lesson only scripts cloud CLIs as “commands that return JSON”, and only does read-only queries | Linux course, Lesson 3 (Azure) · Linux course, Lesson 4 (AWS) |
| The CI/CD platforms themselves (runners, pipeline syntax, environment approvals, OIDC setup details) | This lesson only covers “how to make scripts run reliably in CI” | GitHub, 8 hours · GitLab, 8 hours |
| Desired state across many hosts, idempotent configuration, rolling release orchestration | Beyond a dozen or so hosts, or when idempotency is needed, shell loops are no match for configuration management tools | Ansible, 8 hours |
| Containerized deployment (images, Kubernetes rolling updates) | The deploy target in this lesson is “a single directory”, used to explain the atomic switchover principle | Docker / Kubernetes courses (later in the learning path) |
| bats testing, ShellCheck / shfmt, releasing opsctl v1.0 | Belongs to the next lesson’s topics | Lesson 7 |
| Full systemd unit syntax, journald | This lesson only uses the parts needed for timers | Linux course, Lesson 2 |
python3 -m http.server, and the SSH target can be localhost. All cloud CLI sections are labeled “optional, read-only”.actions/checkout current major version v7. Distro repository versions are usually older (for example, Ubuntu 24.04’s curl is 8.5.0), so this lesson marks options that “need curl ≥ x.y”. macOS ships with Bash 3.2 and BSD tools: mv -T,sha256sum,flock,sort -z etc. require Homebrew’s coreutils / util-linux, or use the alternatives given in this lesson. Ubuntu 26.04 Defaults to the Rust-based coreutils (uutils). The options used in this lesson are all common ones, but please run it once in CI for real (see Module 7).find -print0 | xargs -0, jq). opsctl picks up from the Lesson 4 git tag v0.2.0 and continues from there (Module 0, step 3, describes the interfaces v0.2 provides, such as util::retry,util::lock,util::cleanup_add,config::get etc.; without that tag, first complete the Lesson 3 and 4 capstone labs).linuxlab VM, WSL2, macOS (Homebrew bash + coreutils) or container docker run --rm -it -v "$PWD":/work -w /work bash:5.3 (the official image is based on Alpine, so you need apk add --no-cache curl jq python3 coreutils util-linux tar).~/bashlab, sample data is generated by the Lesson 1 ~/bashlab/make-data.sh script (this lesson uses data/servers.csv,data/inventory.json).curl,jq,python3,flock (util-linux),tar,sha256sum; Module 3 optionally needs GNU parallel and ssh; Module 6 needs systemd (WSL2 needs /etc/wsl.conf enabled systemd=true).sts get-caller-identity and ec2 describe-* with read-only permissions). This lesson creates no cloud resources, so the cost is zero.cd ~/bashlab 2>/dev/null || mkdir -p ~/bashlab && cd ~/bashlab bash --version | head -1 for c in curl jq python3 flock tar sha256sum parallel ssh az aws; do if command -v "$c" >/dev/null; then printf '%-10s ok %s\n' "$c" "$(command -v "$c")" else printf '%-10s -- not installed\n' "$c"; fi done curl --version | head -1
GNU bash, version 5.2.21(1)-release (x86_64-pc-linux-gnu) curl ok /usr/bin/curl jq ok /usr/bin/jq python3 ok /usr/bin/python3 flock ok /usr/bin/flock tar ok /usr/bin/tar sha256sum ok /usr/bin/sha256sum parallel -- not installed ssh ok /usr/bin/ssh az -- not installed aws -- not installed curl 8.5.0 (x86_64-pc-linux-gnu) libcurl/8.5.0 OpenSSL/3.0.13 zlib/1.3 ...
# Debian / Ubuntu sudo apt-get install -y curl jq python3 util-linux parallel openssh-client # macOS (Homebrew): newer bash, GNU coreutils (provides gsha256sum/gmv etc.), flock brew install bash curl jq coreutils flock parallel
--retry-connrefused (7.52.0),--parallel (7.66.0),--retry-all-errors (7.71.0),--fail-with-body (7.76.0),--json (7.82.0),-w '%{header_json}' (7.83.0),-w '%header{name}' (7.84.0),-w '%{num_retries}' (8.9.0). Ubuntu 24.04's curl 8.5.0 does not support the last one (running it reports unknown --write-out variable: 'num_retries').Public test APIs (for example GitHub's unauthenticated endpoints) are rate-limited and flaky, so they are not suitable for practicing retries over and over. This small service, which uses only the Python standard library, can produce on demand 503s, timeouts and pagination:
mkdir -p ~/bashlab/mock && cat > ~/bashlab/mock/mockapi.py <<'PY'
#!/usr/bin/env python3
"""Local mock API for the opsctl course (standard library only).
Usage: python3 mockapi.py [port] default 8000, listens only on 127.0.0.1
GET /healthz -> 200 {"status":"ok"}
GET /items?page=N&per_page=M -> 23 records, paginated, with Link header (next/prev/last)
GET /flaky?fail=K&key=X -> the first K responses for the same key return 503 + Retry-After: 1, then 200
GET /slow?sec=S -> sleeps S seconds, then returns 200
GET /status/CODE -> returns the given status code with a JSON error body
"""
import json, sys, time, threading
from http.server import ThreadingHTTPServer, BaseHTTPRequestHandler
from urllib.parse import urlparse, parse_qs
TOTAL = 23
HITS = {}
LOCK = threading.Lock()
class H(BaseHTTPRequestHandler):
def send_json(self, code, obj, headers=None):
body = (json.dumps(obj) + "\n").encode()
self.send_response(code)
self.send_header("Content-Type", "application/json")
self.send_header("Content-Length", str(len(body)))
for k, v in (headers or {}).items():
self.send_header(k, v)
self.end_headers()
self.wfile.write(body)
def do_GET(self):
u = urlparse(self.path)
q = {k: v[0] for k, v in parse_qs(u.query).items()}
if u.path == "/healthz":
return self.send_json(200, {"status": "ok"})
if u.path == "/items":
page, per = int(q.get("page", 1)), int(q.get("per_page", 10))
last = max(1, -(-TOTAL // per))
start = (page - 1) * per
items = [{"id": i, "name": f"srv-{i:02d}"} for i in range(start + 1, min(start + per, TOTAL) + 1)]
base = f"http://{self.headers.get('Host')}/items?per_page={per}&page="
links = []
if page < last:
links.append(f'<{base}{page + 1}>; rel="next"')
if page > 1:
links.append(f'<{base}{page - 1}>; rel="prev"')
links.append(f'<{base}{last}>; rel="last"')
return self.send_json(200, items, {"Link": ", ".join(links), "X-Total-Count": str(TOTAL)})
if u.path == "/flaky":
fail, key = int(q.get("fail", 2)), q.get("key", "default")
with LOCK:
HITS[key] = HITS.get(key, 0) + 1
n = HITS[key]
if n <= fail:
return self.send_json(503, {"error": "temporarily unavailable", "attempt": n}, {"Retry-After": "1"})
return self.send_json(200, {"status": "ok", "attempt": n})
if u.path == "/slow":
time.sleep(float(q.get("sec", 3)))
return self.send_json(200, {"status": "ok", "slept": q.get("sec", 3)})
if u.path.startswith("/status/"):
code = int(u.path.rsplit("/", 1)[1])
return self.send_json(code, {"error": f"forced {code}"})
return self.send_json(404, {"error": "not found", "path": u.path})
def log_message(self, fmt, *args):
sys.stderr.write("mockapi %s\n" % (fmt % args))
if __name__ == "__main__":
port = int(sys.argv[1]) if len(sys.argv) > 1 else 8000
print(f"mockapi listening on http://127.0.0.1:{port}", flush=True)
ThreadingHTTPServer(("127.0.0.1", port), H).serve_forever()
PY
# start in background, log to file; note the PID for stopping later
python3 ~/bashlab/mock/mockapi.py 8000 2>~/bashlab/mock/mock.log &
echo $! > ~/bashlab/mock/mock.pid
sleep 1; curl -sS http://127.0.0.1:8000/healthz
mockapi listening on http://127.0.0.1:8000
{"status": "ok"}
Stop: kill "$(cat ~/bashlab/mock/mock.pid)". The service only listens on 127.0.0.1 and is not exposed to the network. The /flaky counter is tracked per key key, so use a new key for each exercise (or restart the service) to reset.
This lesson builds on the code delivered by the Lesson 4 capstone lab opsctl v0.2.0 (git tag v0.2.0) and continues from it, with no new starter code. v0.2 already provides all the infrastructure this lesson needs
bin/opsctl: set -Eeuo pipefail + shopt -s inherit_errexit; OPSCTL_HOME (readlink -f parsing, supports ln -s install); readonly OPSCTL_VERSION="0.2.0"; opsctl::list_commands reads each lib/cmd_*.sh 's # opsctl-summary: comments to generate help; opsctl::load_command loads lib/cmd_<name>.sh by name and calls cmd::<name>; util::setup_traps (ERR reporting, EXIT cleanup, signals).lib/log.sh: log::debug/info/warn/error, writes to stderr (format time level opsctl[PID]: message).lib/util.sh: EX_OK/EX_ERR/EX_USAGE/EX_DEP (0/1/2/3),util::die <msg> [code],util::usage_error (exit code 2),util::require_cmd (exit code 3),util::cleanup_add,util::mktemp_dir <var>,util::lock <name> [wait],util::retry <tries> <delay> <cmd…> (exponential backoff + full jitter).lib/config.sh: OPSCTL_DEFAULTS allowlist,config::set_flag / config::get; precedence flag > environment variable OPSCTL_<KEY> > etc/opsctl.conf (key = value, parsed only, never sourced) > defaults.cd ~/bashlab/opsctl git describe --tags; git status --short # expect v0.2.0, and a clean working tree grep -n '^readonly OPSCTL_VERSION=' bin/opsctl export NO_COLOR=1 bin/opsctl -V bin/opsctl help health; echo "rc=$?" # v0.2 does not have health yet
v0.2.0 30:readonly OPSCTL_VERSION="0.2.0" opsctl 0.2.0 2026-11-17T03:01:26-0500 ERROR opsctl[22748]: unknown command: health Try 'opsctl --help' for more information. rc=2
# Azure: browser / device-code login, confirm the current subscription (read-only is enough)
az login --use-device-code
az account show --query '{name:name, id:id, user:user.name}' -o table
# AWS: recommended IAM Identity Center (SSO); confirm identity
aws configure sso # or reuse the configuration from Linux course Lesson 4
aws sts get-caller-identity --query Account --output text
show / list / describe read-only calls, incurring no resource charges (API calls are free, though your organization may bill for audit logs, which you can ignore). When logging in to the cloud from CI, use OIDC (see Module 7).# Use localhost as a “remote host”, to practice the SSH loop at zero cost sudo apt-get install -y openssh-server && sudo systemctl enable --now ssh [[ -f ~/.ssh/id_ed25519 ]] || ssh-keygen -t ed25519 -N '' -f ~/.ssh/id_ed25519 cat ~/.ssh/id_ed25519.pub >> ~/.ssh/authorized_keys && chmod 600 ~/.ssh/authorized_keys ssh -o BatchMode=yes -o StrictHostKeyChecking=accept-new localhost 'hostname; uptime'
curl https://example.com/missing When a 404 is returned, what is the exit code of $? ?0. For curl, “receiving a complete HTTP response” counts as a successful transfer, and a 404 is just response content. Only when adding -f / --fail-with-body , HTTP ≥ 400 turns into exit code 22. This is the first key point of Module 1.
set -e setting, does a failing command inside if cmd; then cause an exit?No. In if/while conditions,&&/|| non-final commands,! or after the negation operator !, errexit is ignored (Bash manual, The Set Builtin). The health checks and retry loops in this lesson rely heavily on this: if ! cmd::health …; then rollback; fi.
--fail-with-body and -w '%{http_code}' to write calls that correctly judge success or failure.--connect-timeout and --max-time, understand that --retry only retries “transient errors” (timeouts, 408 / 429 / 500 / 502 / 503 / 504 etc.), uses exponential backoff by default (starting at 1 second, doubling, capped at 10 minutes) and honors Retry-After.Link: <…>; rel="next" header, merge multi-page results into JSON Lines and pass them to jq.set -e exceptions, plus jq from Lesson 5. Importance:★★★★★ (nearly all ops automation calls APIs)curl is a “transfer tool”: it handles DNS resolution, the TCP / TLS handshake, sends the request and receives the response, then writes the response body to stdout (or to the file given by -o ), writes progress and errors to stderr, and exits with a exit code. The key point is that curl's exit code describes whether the transfer succeeded, not whether the business operation succeeded. A server returning HTTP/1.1 500, for curl, is still “a complete response received”, and the default exit code is 0.
-f, so 404 / 500 HTML error pages are passed to jq as normal JSON, and jq then reports parse error errors, hiding the real cause.--connect-timeout ; the whole transfer is capped by --max-time (timeout → 28).-f (--fail) is set, a status code ≥ 400 → exit code 22 and does not output the response body; --fail-with-body (curl 7.76.0+) also returns 22, but keeps the response body, which is handy for logging the error message the API returns. The two are mutually exclusive.--retry N is given, retries happen): timeouts, FTP 4xx, HTTP 408, 429, 500, 502, 503, 504, 522 and 524 are treated as transient errors; the wait time starts at 1 second by default and doubles each time, capped at 10 minutes; if the response includes Retry-After (since 7.66.0), curl waits for that long. --retry-delay switches to a fixed interval; --retry-max-time caps the total duration of the whole retry process; --retry-connrefused also treats “connection refused” as a transient error; --retry-all-errors (7.71.0) retries every error; the official docs call it a “sledgehammer” and do not recommend using it by default.-w/--write-out prints variables after the transfer ends, for example %{http_code},%{time_total},%{url_effective},%{header_json} (7.83.0),%header{link} (7.84.0),%{num_retries} (8.9.0),%{exitcode} and %{errormsg} (7.75.0).| curl exit code | Meaning | Worth retrying? |
|---|---|---|
| 0 | Transfer succeeded (does not mean HTTP 2xx!) | — |
| 6 | Hostname cannot be resolved | Usually no (configuration error); a few retries are fine if DNS is flaky |
| 7 | Cannot connect (refused / unreachable) | Yes, within a service restart window (--retry-connrefused) |
| 22 | HTTP ≥ 400 (only when -f / --fail-with-body is used) | Check the status code: 5xx / 429 are fine to retry; 4xx (except 408 / 429) should not be retried |
| 28 | Timeout (connect or total time) | Yes, but always with an overall time limit |
| 35 / 60 | TLS handshake failure / certificate verification failure | No; do not use -k to hide |
| 52 / 56 | Empty response / failure to receive data (connection reset) | Yes (common when a backend restarts) |
| Tool | Suited for | Not suited for |
|---|---|---|
| curl | API calls and health checks in scripts; ships with almost every image; exit codes and -w make success or failure easy to judge | Complex auth flows (OAuth refresh), heavy JSON construction |
| wget | Downloading files, recursive mirroring, resumable transfers | REST APIs (less convenient than curl for methods, headers and status handling) |
HTTPie (http) | Interactive debugging with nice output | Scripts (needs extra installation; different exit-code conventions) |
Python requests / Go | Multi-step auth, complex pagination / retry strategies, clients that need unit tests | Glue tasks that take “three lines” |
| Cloud SDKs / CLIs (az, aws) | Cloud vendor APIs: automatic signing, pagination and retries built in | — (see Module 2) |
curl -s “Silent means safe”—-s also hides the error message, so always write -sS (silent progress, but errors still shown). ② “adding --retry 5 means you can survive a 500”— without --max-time , a single request can hang forever and retries never get a chance; without --retry-max-time , exponential backoff can add up to tens of minutes. ③ “-f makes 4xx also get retried”—--retry it only checks whether the status code is on the transient list, so a 404 is never retried (unless --retry-all-errors). ④ “POST can also be retried freely”— non-idempotent requests may create two orders or two VMs on retry, so the API must support idempotency keys or deduplicate at the business level.Pick a scenario and step through the real interaction between the client (curl in the script) and the server: DNS / connection / request / status code / retry decision / sleep / final exit code. The terminal below shows the matching real commands and curl output (verified against this lesson’s mockapi).
| Option | Purpose | Key points / minimum version |
|---|---|---|
-sS | Silent progress bar, but still prints errors | Default choice in scripts |
-f / --fail-with-body | Exit code 22 when HTTP ≥ 400 | The latter keeps the response body (7.76.0); the two are mutually exclusive |
-o FILE / -D FILE | Write response body / headers to a file | -D - Write to stdout |
-w FORMAT | Print variables after the transfer | %{http_code} %{time_total} %header{link} (7.84.0) |
--connect-timeout S | Limits only the connection phase (DNS + TCP + TLS) | Decimals allowed |
-m / --max-time S | Overall time cap for a single transfer | Timeout exit code 28; timer restarts on retry |
--retry N | Retry transient errors N times | Doubles from 1s, capped at 10 minutes; honors Retry-After |
--retry-max-time S | Overall cap on retry duration | No new retries start once reached |
--retry-delay S | Fixed retry interval (turns off exponential backoff) | 0 restores the default |
--retry-connrefused | Also retries when the connection is refused | 7.52.0; useful during service restart windows |
--retry-all-errors | Retry on any error | 7.71.0; use with -f Retries 4xx — use with caution |
--json DATA | POST JSON, sets Content-Type / Accept automatically | 7.82.0; @file / @- |
-H 'Authorization: Bearer …' | Auth header | Use -H @file or --config to keep the token from appearing in ps . |
B=http://127.0.0.1:8000
curl -sS -o /dev/null -w '%{http_code}\n' "$B/status/503"; echo "rc=$?"
curl -fsS "$B/status/404"; echo "rc=$?"
curl -sS --fail-with-body "$B/status/404"; echo "rc=$?"
503
rc=0
curl: (22) The requested URL returned error: 404
rc=22
curl: (22) The requested URL returned error: 404
{"error": "forced 404"}
rc=22
How to verify: The first line shows 503, yet rc=0— this is why scripts that only look at “ $?” treat the failure as success. Common mistakes: Writing both -f --fail-with-body together (mutually exclusive, causes an error). Production use: When a call fails, write the --fail-with-body error JSON you get back to the log, which makes troubleshooting much faster.
# Option A: body to file, status via -w (safest, recommended)
body=$(mktemp)
code=$(curl -sS -o "$body" -w '%{http_code}' --connect-timeout 3 --max-time 10 "$B/status/422") || code=000
echo "code=$code"; jq -r '.error' "$body"; rm -f "$body"
# Option B: append the status code on the last line, then split it with parameter expansion
resp=$(curl -sS -w '\n%{http_code}' "$B/status/422")
code=${resp##*$'\n'}; body=${resp%$'\n'*}
echo "code=$code body=$body"
code=422
forced 422
code=422 body={"error": "forced 422"}
Option B also works when the response body itself does not end with a newline; but large responses stay whole in a variable, and binary content gets truncated by Bash (NUL bytes), so for downloads always use Option A. || code=000 Handling transfer failures (here curl still prints 000).
curl -sS -o /dev/null \
-w 'code=%{http_code} total=%{time_total}s connect=%{time_connect}s url=%{url_effective}\n' \
"$B/healthz"
code=200 total=0.000661s connect=0.000094s url=http://127.0.0.1:8000/healthz
curl -sS --max-time 1 "$B/slow?sec=3"; echo "rc=$?" curl -fsS --retry 3 "$B/flaky?fail=2&key=demo1"; echo "rc=$?" curl -S --retry 3 -o /dev/null "$B/flaky?fail=2&key=demo2" # without -s, you can see the retry notices curl -sS --retry 2 --retry-connrefused --retry-delay 1 http://127.0.0.1:9; echo "rc=$?"
curl: (28) Operation timed out after 1001 milliseconds with 0 bytes received
rc=28
{"status": "ok", "attempt": 3}
rc=0
Warning: Problem : HTTP error. Will retry in 1 seconds. 3 retries left.
…(each retry afterwards prints one line, eventually succeeds)
curl: (7) Failed to connect to 127.0.0.1 port 9 after 1 ms: Couldn't connect to server
curl: (7) Failed to connect to 127.0.0.1 port 9 after 0 ms: Couldn't connect to server
curl: (7) Failed to connect to 127.0.0.1 port 9 after 0 ms: Couldn't connect to server
rc=7
Note: When retrying, without and without -f , -o the response body of every failed attempt goes to stdout, so you get three JSON documents concatenated (verified). Adding -f discards the failed response bodies and keeps only the last successful result; when using -o file , curl truncates the file before each retry.
# Recommended production combo (GET / idempotent requests)
curl -fsS --connect-timeout 3 --max-time 10 \
--retry 4 --retry-max-time 60 --retry-connrefused \
-H 'Accept: application/json' "$url"
curl -sS -o /dev/null -w '%header{link}\n' "$B/items?per_page=10&page=1" # curl ≥ 7.84
<http://127.0.0.1:8000/items?per_page=10&page=2>; rel="next", <http://127.0.0.1:8000/items?per_page=10&page=3>; rel="last"
# Compatible with older curl: use -D to write headers to a temp file, then extract rel="next" with sed
api::get_all() { # usage: api::get_all URL → outputs all page elements as JSON Lines
local url=$1 hdr body
hdr=$(mktemp)
while [[ -n $url ]]; do
body=$(curl -fsS --retry 3 --connect-timeout 3 --max-time 10 -D "$hdr" "$url") \
|| { rm -f "$hdr"; return 1; }
jq -c '.[]' <<<"$body"
url=$(tr -d '\r' <"$hdr" | sed -n 's/^[Ll]ink:.*<\([^>]*\)>; *rel="next".*/\1/p')
done
rm -f "$hdr"
}
api::get_all "$B/items?per_page=10" | sed -n '1,3p'
api::get_all "$B/items?per_page=10" | wc -l
{"id":1,"name":"srv-01"}
{"id":2,"name":"srv-02"}
{"id":3,"name":"srv-03"}
23
Key points: HTTP headers end with \r\n , so you must first strip it with tr -d '\r', otherwise the URL ends with \r, and the next request returns 400. Header names are case-insensitive (lowercase under HTTP/2 link:), so use [Ll]ink. Do not use | head -3 to truncate — under set -o pipefail , the upstream killed by SIGPIPE makes the whole pipeline fail (verified: Python reports BrokenPipeError), the 141 problem from Lesson 4.
idem=$(cat /proc/sys/kernel/random/uuid) # one key per “business operation”, reuse on retry
jq -n --arg name "web-03" --arg env prod '{name:$name, env:$env}' |
curl -sS --fail-with-body --max-time 15 \
-H "Idempotency-Key: $idem" \
-H @"$HOME/.config/opsctl/auth.header" \
--json @- https://api.example.com/v1/servers
Use jq -n --arg to build the JSON, avoiding quoting and injection problems from hand-concatenated strings. -H @file (curl 7.55.0+) reads headers from a file, so the token never appears in ps output or shell history. Whether Idempotency-Key is supported depends on the API (Stripe and others support it); if it is not supported,Do not use on POST --retry.
B=http://127.0.0.1:8000; curl -sS "$B/healthz"
curl -sS "$B/status/500" >/dev/null; echo "no -f: rc=$?" curl -fsS "$B/status/500" >/dev/null; echo "with -f: rc=$?"
no -f: rc=0 curl: (22) The requested URL returned error: 500 with -f: rc=22
~/bashlab/m1-api.sh):
cat > ~/bashlab/m1-api.sh <<'EOF'
#!/usr/bin/env bash
set -euo pipefail
B=${B:-http://127.0.0.1:8000}
# api::call METHOD PATH → prints response body to stdout; returns 1 when the status code is not 2xx, and writes the error body to stderr
api::call() {
local method=$1 path=$2 body code
body=$(mktemp)
code=$(curl -sS -X "$method" -o "$body" -w '%{http_code}' \
--connect-timeout 3 --max-time 10 \
--retry 4 --retry-max-time 30 --retry-connrefused \
"$B$path") || code=000
if [[ $code == 2?? ]]; then
cat "$body"; rm -f "$body"; return 0
fi
printf 'api::call %s %s → HTTP %s: %s\n' "$method" "$path" "$code" "$(head -c 300 "$body")" >&2
rm -f "$body"; return 1
}
api::call GET /healthz
api::call GET "/flaky?fail=2&key=lab-$$"
api::call GET /status/404 || echo "→ 404 correctly identified as failure (rc=$?)"
EOF
bash ~/bashlab/m1-api.sh
{"status": "ok"}
{"status": "ok", "attempt": 3}
api::call GET /status/404 → HTTP 404: {"error": "forced 404"}
→ 404 correctly identified as failure (rc=1)
Why did /flaky succeed? Because --retry automatically handled the first two 503s and honored Retry-After: 1. [[ $code == 2?? ]] Use a wildcard to match all 2xx.
/slow?sec=15 to the script and observe about 10 seconds later HTTP 000; then change --max-time to 20 and observe success. Think about: --retry 4 what is the longest wait time? (Hint: each attempt takes up to 10 seconds plus backoff, but --retry-max-time 30 the overall limit (about 30 seconds) stops new attempts from starting.)api::get_all from the “Commands” page to the script, count the items and take the last 3 by name:
api::get_all "$B/items?per_page=7" | jq -r '.name' | sort | tail -n 3
srv-21 srv-22 srv-23
curl -sS -o /dev/null -D - 'https://api.github.com/orgs/bminor/repos?per_page=2' \ | grep -iE '^(link|x-ratelimit-remaining):'
x-ratelimit-remaining: 57 link: <https://api.github.com/organizations/…/repos?per_page=2&page=2>; rel="next", <…&page=…>; rel="last"
tail ~/bashlab/mock/mock.log You can see each retry request; this module has no resources to clean up (mockapi is still needed later, so do not stop it yet).Problem: The monitoring script curl -s http://svc/healthz && echo OK has never raised an alarm over the years. After a release, the app returned 500 with an error page; curl's exit code stayed 0, and users only discovered the outage 40 minutes later. Fix: Change it to curl -fsS --max-time 5 -o /dev/null -w '%{http_code}', explicitly compare against the expected status code, and write the first 300 bytes of the response body to the log. Limitations: A 200 status can still mean a “degraded” state, so the health endpoint should ideally return structured JSON (such as {"status":"ok","db":"ok"}) and validate key fields with jq.
Problem: Cron on 200 hosts all call the config center at second 0 of every minute; after the config center briefly returns 503, every script retries 10 times at a fixed 1-second interval, multiplying request volume 10x in an instant and taking the config center down completely. Fix:① exponential backoff (curl default) + random jitter (sleep "$((RANDOM % 30))" or systemd’s RandomizedDelaySec); ② honor Retry-After; ③ --retry-max-time cap the total duration; ④ the server returns 429 so clients back off. Limitations: Jitter adds per-attempt latency; for latency-sensitive tasks, this is a trade-off.
Problem: The “clean up untagged snapshots” script only read the first page of the API (100 items) and treated “snapshots not in the list” as orphans and deleted them. Fix: Fully paginate by Link: rel="next" or the API’s nextToken pagination; verify counts before deleting (compare with X-Total-Count or a second query); print a dry-run list first and confirm it manually. Configuration: This module’s api::get_all. Limitations: Data may change during pagination (new / deleted items), so critical operations should re-confirm based on snapshot IDs.
Cause: The API returned an HTML error page with a 4xx/5xx status (or a proxy’s login page), and curl did not -f, so it was handed to jq as normal output.
curl -sS -D - -o /tmp/body "$url" | head -5; head -c 300 /tmp/body
Fix: Add --fail-with-body, or first check %{http_code} and %{content_type} before handing it to jq.
Cause: The connection succeeded, but the server did not respond within --max-time (slow query, deadlock, or packet loss at a network middlebox). If the message is “Connection timed out after … milliseconds”, it is stuck in the connect phase (firewall / security group dropping packets).
curl -sS -o /dev/null -w 'dns=%{time_namelookup} connect=%{time_connect} tls=%{time_appconnect} ttfb=%{time_starttransfer} total=%{time_total}\n' "$url"
Fix: Locate it using the per-phase times: connect large → network / security group; ttfb large → the server is slow to process. Set sensible values for --connect-timeout (3–5 seconds) and --max-time, and investigate on the server side.
Cause: The container or minimal image lacks a CA certificate bundle, or the corporate proxy performs TLS interception.
ls /etc/ssl/certs/ca-certificates.crt; curl -v "$url" 2>&1 | grep -E 'issuer|CAfile'
Fix: Install ca-certificates; for a corporate CA, use --cacert corp-ca.pem or add it to the system trust store. Do not use -k/--insecure in scripts.
Cause:%{num_retries} Needs curl 8.9.0+; Ubuntu 24.04's 8.5.0 does not support it (verified). Likewise %header{…} needs 7.84.0+.
curl --version | head -1
Fix: Check the version at the start of the script, or switch to a compatible approach (-D header file + sed); use a pinned-version image in CI.
Cause: The URL extracted from the header file ends with \r; or the sed regex treats rel="last" as next, so it keeps requesting the last page.
printf '%q\n' "$url" # if $'\r' appears at the end, this is the problem
Fix:tr -d '\r'; anchor the regex rel="next"; add a maximum-page guard to the loop (for example, 1000 pages).
$url, with a 3-second connect timeout and a 10-second overall timeout, retries transient errors up to 3 times with total retry time capped at 30 seconds, and when HTTP ≥ 400 exits non-zero but keeps the error body.curl -sS --fail-with-body --connect-timeout 3 --max-time 10 \
--retry 3 --retry-max-time 30 "$url"$url the status code and total time (no response body), and, when the transfer fails, print 000.curl -sS -o /dev/null -w '%{http_code} %{time_total}\n' --max-time 5 "$url" || true
# when the transfer fails, curl still prints 000 via -w; || true stops set -e from exiting--retry 5 --retry-all-errors to the POST call that creates a DNS record, and duplicate records appear occasionally. Analyze the cause and propose an improvement.Cause: --retry-all-errors will retry after any error, including when “the request was processed by the server but the response timed out on the way back” (the client sees 28), so the same POST runs multiple times. POST is non-idempotent. Improvements: ① remove --retry-all-errors, so POST is never retried automatically; ② if the API supports idempotency keys, generate one Idempotency-Key and reuse it on retries; ③ switch to “check whether it exists first, then create” (or use an API with PUT / upsert semantics); ④ check the resource state before retrying.
--retry,--fail-with-body,--write-out Variables and version requirementsThis course material cannot generate video / MP3 directly, but storyboards and narration scripts are provided for a video tool to produce it.
curl -s …/healthz; echo $? output a 500 error page and 0; the frame flashes red.-f then 500 turns into exit code 22.--filters,--resource-group,--tag) and client-side filtering (--query JMESPath, jq) and their order.-o tsv (az) / --output text (aws) + while IFS=$'\t' read -r to read results safely into Bash variables and arrays, and know when to switch to -o json | jq -r … | @tsv.AWS_PAGER="" / --no-cli-pager), automatic pagination and --output text interaction, the Windows az output’s \r, quoting differences, and region / subscription defaults.--only-show-errors.az and aws are programs that “call the REST API → get JSON → optionally filter with JMESPath (--query) → format by --output format”. JMESPath is a JSON query language (Reservations[].Instances[].InstanceId,[?state=='running'],{name:name}), and both CLIs have the same syntax built in. Microsoft Learn explicitly states that az's query is applied client-side to the returned JSON before display formatting.
-o table is meant for humans: column widths get truncated, and column order and headings may change between versions.id=$(az … --query id) you get "0000…" (including the quotes), and passing it to the next command gives “doesn't exist” — the typical example in the official troubleshooting docs.less), so in scripts and CI without a terminal it can hang or misbehave.aws ec2 describe-instances --filters Name=instance-state-name,Values=running,az vm list -g rg-x,az resource list --tag env=prod.--query: select fields, do simple filtering and renaming, and output tsv/text straight to Bash. No extra dependencies needed.group_by,any(), variables --arg, string handling, merging several files) with -o json | jq.| Dimension | Azure CLI (az) | AWS CLI v2 (aws) |
|---|---|---|
| Machine-readable plain text | -o tsv (multi-select fields need a list [a,b] to guarantee column order) | --output text (lists go one per row, fields separated by Tab) |
| Default output format config | az config set core.output=json or environment variable AZURE_CORE_OUTPUT | AWS_DEFAULT_OUTPUT or ~/.aws/config ’s output |
| pagination (API layer) | Most list commands fetch everything automatically | , fetch all pages by default; --no-paginate,--max-items,--page-size,--starting-token |
| terminal pager | None | v2 enables it by default; AWS_PAGER="" or --no-cli-pager to disable |
| Quiet mode | --only-show-errors (hides warnings) | — (warnings go to stderr) |
| Failure exit codes | non-zero (follow the official docs) | 252 syntax / 253 config or credentials / 254 service error / 255 other; 130 Ctrl-C |
| Debugging | --debug (prints HTTP requests and responses) | --debug |
--output text , the output will paginate first, and then --query runs on each page separately, which may produce unexpected extra output (for example, [0] returns only the first item of each page). For queries over the whole result set, use --output json.| Scenario | Recommended |
|---|---|
| Read-only checks, reports, providing a single value to CI (subscription ID, image ID, IP) | Bash + CLI + --query |
| Creating / modifying resources that must be repeatable and reviewable | Terraform / Bicep / CloudFormation (IaC) |
| Heavy concurrent calls, complex retries, need for unit tests | Python SDK (azure-*, boto3) |
| Configuring many hosts | Ansible (azure.azcollection,amazon.aws) |
--query “--query can reduce API calls”— no, it runs on the client after all the data has been downloaded; to reduce the data volume, use server-side filtering. ② “-o tsv The column order of {a:…,b:…} is the order I wrote in the query”— object (dict) order is not guaranteed in tsv, so use a list [a, b]. ③ “JMESPath and jq have the same syntax”— the filter syntax is completely different (JMESPath literals use backticks `running` or single-quoted strings 'running'), so do not mix them. ④ “an az command copied from Windows also works in Bash”— quoting rules differ (PowerShell strips brackets and quotes; verified length(@) in PowerShell parses it incorrectly).Data: a trimmed-down aws ec2 describe-instances output (3 instances, one with a space in its name and one stopped). After choosing a method, step through what each layer does to the data and what value Bash finally gets. The jq column output comes from local runs (jq 1.6 and 1.8 give the same result).
| Command | Purpose | Key parameters |
|---|---|---|
az account show --query id -o tsv | Current subscription ID | -o tsv Strip quotes |
az vm list -d --query "[?powerState=='VM running'].[name,resourceGroup]" -o tsv | Running VMs | -d with power state and IP (makes extra API calls, so slower) |
az resource list --tag env=prod --query "[].id" -o tsv | Find resources by tag | Tag filtering happens server-side |
aws sts get-caller-identity --query Account --output text | Current account | the cheapest “who am I” check |
aws ec2 describe-instances --filters … --query … --output text | Instance inventory | --filters Server-side; --query Client-side |
aws ec2 describe-regions --query 'Regions[].RegionName' --output text | Region list | Note that text output puts each record on a single line with fields separated by tabs |
AWS_PAGER="" aws … / --no-cli-pager | Turn off the v2 pager | Required for scripts / CI |
jq -r '…|@tsv',jq -e,jq --arg | Complex processing | -e: exit code 1 when the result is null/false |
az cloud list --query "[].{name:name, active:isActive, arm:endpoints.resourceManager}" -o tsv
az cloud list --query "[?isActive].name" -o tsv
az cloud show -n AzureCloud --query "endpoints.activeDirectory" -o tsv
az cloud show -n NoSuch; echo "rc=$?"
AzureCloud True https://management.azure.com/ AzureChinaCloud False https://management.chinacloudapi.cn AzureUSGovernment False https://management.usgovcloudapi.net/ AzureGermanCloud False https://management.microsoftazure.de AzureCloud https://login.microsoftonline.com ERROR: The cloud 'NoSuch' is not registered. rc=1
Note that the first example uses an object {…}: here the column order happens to match the order written, but the official docs don't guarantee it, so use a list in scripts [name, isActive, endpoints.resourceManager]. The cloud list may differ between CLI versions.
set -euo pipefail
export AZURE_CORE_OUTPUT=json # Prevents a user's default output from being changed to table and breaking the script
sub=$(az account show --query id -o tsv)
echo "subscription=$sub"
# Running VMs: name, resource group, private IP (list → fixed column order)
while IFS=$'\t' read -r name rg ip; do
printf '%-20s %-18s %s\n' "$name" "$rg" "$ip"
done < <(az vm list -d --only-show-errors \
--query "[?powerState=='VM running'].[name, resourceGroup, privateIps]" -o tsv)
# Resource group count (JMESPath function)
az group list --query "length(@)" -o tsv
subscription=00000000-0000-0000-0000-000000000000 vm-linux-lab rg-linux-lab 10.10.1.4 3
set -euo pipefail
export AWS_PAGER="" # Turn off the v2 pager
export AWS_REGION=${AWS_REGION:-ca-central-1}
acct=$(aws sts get-caller-identity --query Account --output text)
echo "account=$acct region=$AWS_REGION"
aws ec2 describe-instances \
--filters Name=instance-state-name,Values=running \
--query 'Reservations[].Instances[].[InstanceId, Tags[?Key==`Name`]|[0].Value, PrivateIpAddress]' \
--output text |
while IFS=$'\t' read -r id name ip; do
printf '%s %-12s %s\n' "$id" "$name" "$ip"
done
account=123456789012 region=ca-central-1 i-0a1b2c3d4e5f60001 web-01 10.0.1.11 i-0a1b2c3d4e5f60003 api 01 10.0.2.21
JMESPath backtick literals `Name` must go inside Bash single quotes or Bash will treat them as command substitution. Instances without a Name tag,|[0].Value return null, and text output shows None.
# ec2.json: trimmed describe-instances sample (3 instances; the name of api 01 contains a space, web-02 is stopped)
jq -r '.Reservations[].Instances[] | select(.State.Name=="running")
| [.InstanceId, (.Tags[]? | select(.Key=="Name") | .Value), .PrivateIpAddress] | @tsv' ec2.json
# Count instances per state
jq -c '[.Reservations[].Instances[]] | group_by(.State.Name) | map({state: .[0].State.Name, n: length})' ec2.json
# Pass variables safely with --arg (don't concatenate Bash variables into the filter string)
jq -r --arg env prod '.Reservations[].Instances[]
| select(any(.Tags[]?; .Key=="env" and .Value==$env)) | .InstanceId' ec2.json
mapfile -t ids < <(jq -r '.Reservations[].Instances[].InstanceId' ec2.json)
echo "${#ids[@]} ${ids[2]}"
i-0a1b2c3d4e5f60001 web-01 10.0.1.11
i-0a1b2c3d4e5f60003 api 01 10.0.2.21
[{"state":"running","n":2},{"state":"stopped","n":1}]
i-0a1b2c3d4e5f60001
i-0a1b2c3d4e5f60002
3 i-0a1b2c3d4e5f60003
aws_ro() { # Read-only aws call: report the failure reason in readable form
local out rc=0
out=$(aws --no-cli-pager "$@" 2>&1) || rc=$?
case $rc in
0) printf '%s\n' "$out" ;;
253) log::error "AWS credentials or configuration is invalid: $out"; return 3 ;;
254) log::error "AWS service rejected the request (permissions / parameters): $out"; return 1 ;;
252) log::error "Command syntax error: $out"; return 2 ;;
*) log::error "aws failed rc=$rc: $out"; return 1 ;;
esac
}
aws_ro sts get-caller-identity --query Arn --output text
Note: 2>&1 Merging errors into out makes logging easier. On success, any warnings also get mixed into the output, so only use this pattern for commands that return a single value; otherwise write stderr to a temp file. The exit code meanings come from the AWS CLI User Guide, “Command line return codes”.
mkdir -p ~/bashlab/m2 && cd ~/bashlab/m2
cat > ec2.json <<'EOF'
{"Reservations":[
{"Instances":[{"InstanceId":"i-0a1b2c3d4e5f60001","InstanceType":"t3.micro","State":{"Name":"running"},"PrivateIpAddress":"10.0.1.11","Tags":[{"Key":"Name","Value":"web-01"},{"Key":"env","Value":"prod"}]},
{"InstanceId":"i-0a1b2c3d4e5f60002","InstanceType":"t3.small","State":{"Name":"stopped"},"PrivateIpAddress":"10.0.1.12","Tags":[{"Key":"Name","Value":"web-02"},{"Key":"env","Value":"prod"}]}]},
{"Instances":[{"InstanceId":"i-0a1b2c3d4e5f60003","InstanceType":"t3.micro","State":{"Name":"running"},"PrivateIpAddress":"10.0.2.21","Tags":[{"Key":"Name","Value":"api 01"},{"Key":"env","Value":"staging"}]}]}
]}
EOF
jq '.Reservations | length' ec2.json
2
ids=(); names=(); ips=()
while IFS=$'\t' read -r id name ip; do
ids+=("$id"); names+=("$name"); ips+=("$ip")
done < <(jq -r '.Reservations[].Instances[] | select(.State.Name=="running")
| [.InstanceId, (.Tags[]? | select(.Key=="Name") | .Value // "-"), .PrivateIpAddress // "-"] | @tsv' ec2.json)
for i in "${!ids[@]}"; do printf '%s → %s\n' "${names[i]}" "${ips[i]}"; done
web-01 → 10.0.1.11 api 01 → 10.0.2.21
~/bashlab/data/inventory.json has the same content as servers.csv (fields name / env / region / ip / role).
jq -r '.[] | select(.env=="prod") | [.name, .region, .ip] | @tsv' ~/bashlab/data/inventory.json
Output depends on your dataset (example). Think about it: does the line with a quoted comma still need special handling in JSON? (No. That is exactly why “CSV has boundary problems, JSON doesn't.”)
az account show --query "{sub:name, tenant:tenantId}" -o jsonc
az group list --query "[].[name, location]" -o tsv | sort
az vm list -d --query "[].[name, powerState]" -o tsvexport AWS_PAGER="" AWS_REGION=ca-central-1 aws sts get-caller-identity --output json aws ec2 describe-regions --query 'Regions[].RegionName' --output text | tr '\t' '\n' | sort | head aws ec2 describe-instances --query 'length(Reservations[].Instances[])' --output json
rm -rf ~/bashlab/m2. All cloud calls in this module are read-only, so there are no cloud resources to delete.Problem: After upgrading to AWS CLI v2, a script running on a self-hosted runner (with a pseudo-TTY allocated) calls aws ec2 describe-instances, and its output is passed to less, so the job waits for a keypress until it times out. Fix: Set it at the top of the script export AWS_PAGER="", or in the ~/.aws/config settings cli_pager=, or add it to each command --no-cli-pager. Limitations: It only affects the CLI's own pager and does not affect API pagination.
Problem:sub=$(az account list --query "[?name=='prod'].id") Got [ "…" ] (a JSON array),az account set -s "$sub" failed, but the script did not set -e, and subsequent commands ran on the current default subscription (the test subscription). Fix:① Use -o tsv and [0] to get a single value; ② validate the format [[ $sub =~ ^[0-9a-f-]{36}$ ]]; ③ pass the subscription explicitly on every command --subscription "$sub", instead of relying on the global default. Limitations: When multiple subscriptions share the same name, [0] it returns an arbitrary one; names should be unique, or use IDs instead.
Problem: A developer in Git Bash calls the Windows version of az,-o tsv whose output lines each end with \r\n , and the variable value ends with \r, so the next command reports “ResourceNotFound”. Fix: Install the Linux build of az in WSL, or | tr -d '\r'; when troubleshooting, use printf '%q\n' "$var" to see $'abc\r' (verified). Limitations: When JSON output is parsed by jq \r counts as whitespace, so the impact is minor.
Cause: The variable holds JSON (with quotes / brackets), not a plain value.
printf '%q\n' "$sub"
Fix:--query "[0].id" -o tsv or -o json | jq -r '.[0].id'.
Cause: Quotes / brackets in the query were rewritten by the shell (PowerShell especially), or jq syntax was mixed in (select(),== followed by a double-quoted string)
az vm list --query "[?powerState=='VM running'].name" -o tsv --debug 2>&1 | grep -m1 'Command arguments'
Fix: In Bash, wrap the whole query in double quotes and string literals in single quotes; or put the query in a variable q="…" then use --query "$q".
Cause: No credential source is available in the current environment (environment variables, SSO cache, config file, instance role), or the SSO token has expired.
aws configure list; aws sts get-caller-identity; echo "rc=$?"
Fix:aws sso login --profile …; in CI, use an OIDC role (Module 7). In scripts, show a “log in” hint for code 253 (see the “Commands” tab's aws_ro).
Cause: Credentials are valid, but the IAM policy does not allow the operation, or the region is restricted by an SCP.
aws sts get-caller-identity --query Arn --output text
Fix: Add least-privilege read-only permissions to the role (for example ec2:Describe*); confirm AWS_REGION.
Cause: Tab is an IFS whitespace character,consecutive tabs are merged, so empty fields disappear.
printf 'a\t\tc\n' | while IFS=$'\t' read -r x y z; do printf '[%s][%s][%s]\n' "$x" "$y" "$z"; done # [a][c][]
Fix: Add a placeholder for empty values in jq / JMESPath (jq: .x // "-"; JMESPath: not_null(x, '-')), or switch to @json one object per line, then parse each one individually.
rgs, and print the count.mapfile -t rgs < <(az group list --query "[].name" -o tsv | tr -d '\r')
echo "${#rgs[@]}"aws ec2 describe-instances --region ca-central-1 --no-cli-pager \ --filters Name=instance-state-name,Values=stopped \ --query 'Reservations[].Instances[].InstanceId' --output text | tr '\t' '\n'
Possible causes and how to check: ① only used the --query of [0] or --output text + --query in each page (AWS), so behavior changes as result sets grow. Switch to JSON output + jq or server-side filtering; --max-items / --no-paginate; ③ tag values differ in case (e.g. Dev vs dev), JMESPath and server-side filtering are case-sensitive; ④ empty fields in the TSV shift columns, so some VMs' names are read as empty; ⑤ some VMs are in another subscription or region. Improvements: log the “number queried” and the “number successfully processed” and alert on any mismatch; check the exit code for each VM operation; use dry-run mode to print the list first.
About az --query / aws --query (JMESPath) scripting: No verified video found (all search results are text tutorials); refer to the official docs below, and make your own video from the storyboard script.
This courseware cannot directly generate a video or MP3, so a storyboard and narration script are provided.
id=$(az … --query id) after echo $id shows a quoted value, and the next command errors.less The pager hangs the CI log, then add AWS_PAGER="" , and the job then finishes successfully.while read a loop ssh only processes the first host (ssh reads the loop's stdin), and fix it with ssh -n / </dev/null .xargs -0 -P N and GNU parallel -j N --joblog --tag to run in parallel, and understand their exit codes (xargs 123, parallel = number of failed jobs).BatchMode=yes,ConnectTimeout,StrictHostKeyChecking=accept-new, write each host's stdout, stderr and exit code to separate files, and summarize them.find -print0 | xargs -0 from Lesson 5. Priority:★★★★☆cmd & + wait (in Bash 5.1+, wait -n -p var can get the PID of the first job to finish) — no dependencies needed, but you must control concurrency yourself.--joblog (start time, duration, exit code of each job),--tag (prefixes output with the hostname), output grouped per job without interleaving,--retries,--timeout,--halt,--results directory. The exit code is the number of failed jobs (1–100); above 100 it is 101.while read h; do ssh "$h" uptime; done < hosts— ssh by default forwards the local stdin to the remote host, so the first call reads all the remaining lines of hosts and the loop runs only once (verified: with 3 lines, only h1 was processed).ssh -n -o BatchMode=yes -o ConnectTimeout=5 -o StrictHostKeyChecking=accept-new, and when needed, wrap it with timeout 60.xargs -P or parallel -j, set based on what the target system can handle (for example, API rate limits or bastion connection counts).results/<host>.out|.err|.rc, or use parallel's --joblog / --results; finally summarize the success / failure lists, and exit non-zero when the failure count > 0.| Approach | Dependencies | Concurrency control | Result collection | Best for |
|---|---|---|---|---|
& + wait | None | Write your own semaphore (wait -n) | Write your own | Small fixed set of tasks |
xargs -P | findutils (almost always installed) | -P N | Only the summary exit code (123) | Simple batch jobs, containers / CI |
GNU parallel | Requires installation (Perl) | -j N,--load,--delay | --joblog,--results,--tag | Batch ops work that needs reports |
| Ansible ad-hoc / playbook | Ansible | forks,serial | structured results, idempotent | Config changes, rolling releases |
Read-only inspection (version, disk, certificate expiry) is fine with an SSH loop; once you need to change state (install packages, change config, restart services) and need idempotency, a dry run (--check), rolling batches (serial) and failure-rate control, switch to Ansible.
-P 0 Faster is better”—in GNU xargs -P 0 means “as many as possible”, which can open hundreds of SSH connections at once and trigger sshd’s MaxStartups limit (extra connections get rejected at random). ② “xargs exit code 0 means everything succeeded”—exit 0 only happens when all calls succeed, but it does not tell you which host failed, so you must record it yourself. ③ “Adding & makes it a parallel script”—without wait , the script exits early, so the results and exit code are lost. ④ “StrictHostKeyChecking=no saves effort”—it accepts tampered host keys; use accept-new (only auto-accepts first-time seen hosts; a changed known host key is still rejected).8 hosts, each taking a different amount of time, of which db-01 is unreachable (waits for ConnectTimeout=5 before failing, rc=255). Drag the concurrency level to observe the scheduling timeline (consistent with the “start the next one as soon as a slot frees up” scheduling of xargs / parallel), the total time, and the final exit code.
| Command / option | Purpose | Key points |
|---|---|---|
xargs -0 -P 4 -n 1 | NUL-separated, 4 concurrent jobs, one argument per call | any call with rc 1–125 → final 123; killed by a signal → 125 |
xargs -I{} | Replacement string | Implicit -L 1 (one per line); with -0 When used together, use NUL |
parallel -j 8 --joblog f --tag | Parallel + job log + output prefix | Output is grouped by job by default, no interleaving |
parallel --timeout 60 --retries 2 | Job timeout / retries | --timeout 200% means 2× the median runtime |
parallel --halt soon,fail=10% | Stop dispatching when too many fail | “Circuit breaker” for rolling operations |
ssh -n | stdin comes from /dev/null | Required in loops; also needed for background runs |
-o BatchMode=yes | Disable all interactive prompts | Fail immediately when a password is needed (rc 255) |
-o ConnectTimeout=5 | Connection timeout | No limit on command run time (use timeout) |
-o StrictHostKeyChecking=accept-new | Automatically accept host keys on first connection | OpenSSH 7.6+; still rejects changed known keys |
ssh host bash -s -- args < script.sh | Run a local script on a remote host | In this case,you cannot add -n (the script is sent via stdin). |
printf 'h1\nh2\nh3\n' > /tmp/hosts.txt # sh -c 'cat >/dev/null' simulates ssh: reads and forwards stdin while read -r h; do echo "processing $h"; sh -c 'cat >/dev/null'; done < /tmp/hosts.txt echo --- while read -r h; do echo "processing $h"; sh -c 'cat >/dev/null' </dev/null; done < /tmp/hosts.txt
processing h1 --- processing h1 processing h2 processing h3
SSH_OPTS=(-n -o BatchMode=yes -o ConnectTimeout=5 -o StrictHostKeyChecking=accept-new
-o ServerAliveInterval=10 -o ServerAliveCountMax=3)
fail=0
while IFS= read -r host; do
[[ -z $host || $host == \#* ]] && continue
if out=$(timeout 60 ssh "${SSH_OPTS[@]}" "$host" 'uname -r; df -h / | tail -1' 2>&1); then
printf '%-12s OK %s\n' "$host" "$(tr '\n' ' ' <<<"$out")"
else
rc=$?; ((++fail))
printf '%-12s FAIL rc=%s %s\n' "$host" "$rc" "$out" >&2
fi
done < hosts.txt
((fail == 0)) || { echo "$fail host(s) failed" >&2; exit 1; }
if out=$(…); then … else rc=$?: in the first command of the else branch $? still holds the exit code of the conditional command (here, a command substitution). ((++fail)) Use pre-increment: ((fail++)) When fail=0, the expression evaluates to 0 and the exit code is 1, which triggers set -e (covered in Lesson 4). An ssh-level error (connection failure, authentication failure) exits with 255; when the remote command fails, ssh returns that command's exit code; timeout a timeout returns 124.
R=$(mktemp -d)
run_one() { # run_one name URL results-dir
local name=$1 url=$2 R=$3
if curl -fsS -o "$R/$name.out" --max-time 3 "$url" 2>"$R/$name.err"; then
echo 0 >"$R/$name.rc"
else
echo $? >"$R/$name.rc"
fi
}
export -f run_one
printf '%s\t%s\n' web-01 http://127.0.0.1:8000/healthz web-02 http://127.0.0.1:8000/status/503 \
"api 01" http://127.0.0.1:8000/healthz db-01 http://127.0.0.1:9/ |
tr '\t\n' '\0\0' |
xargs -0 -n 2 -P 4 bash -c 'run_one "$2" "$3" "$1"' _ "$R"
for f in "$R"/*.rc; do n=${f##*/}; printf '%-8s rc=%s\n' "${n%.rc}" "$(<"$f")"; done
api 01 rc=0 db-01 rc=7 web-01 rc=0 web-02 rc=22
Key points: ① bash -c '…' _ "$R" in _ occupies $0, and the two arguments xargs appends become $2 $3 ($1 the results directory); ② the function needs export -f to be available in bash -c child processes; ③ use NUL separation, so spaces in names (api 01) are not split; ④ pass task data as arguments passed in, rather than concatenated into bash -c the script string; the latter carries injection risk.
printf '%s\n' /healthz /status/500 /healthz |
xargs -P 2 -I{} curl -fsS -o /dev/null "http://127.0.0.1:8000{}"; echo "xargs rc=$?"
time (printf '%s\n' 1 2 3 4 5 6 | xargs -P 3 -I{} curl -fsS -o /dev/null "http://127.0.0.1:8000/slow?sec=1&p={}")
curl: (22) The requested URL returned error: 500 xargs rc=123 real 0m2.031s
6 tasks, each taking 1 second, 3 running concurrently → about 2 seconds.
jq -r '.[] | select(.env=="prod") | .ip' ~/bashlab/data/inventory.json > prod-hosts.txt
parallel -j 8 --tag --timeout 60 --joblog jobs.tsv \
ssh -n -o BatchMode=yes -o ConnectTimeout=5 -o StrictHostKeyChecking=accept-new {} \
"'uptime -p; systemctl is-active myapp || true'" :::: prod-hosts.txt
echo "failed jobs=$?"
column -t -s $'\t' jobs.tsv | head # Seq Host Starttime JobRuntime Send Receive Exitval Signal Command
awk -F'\t' 'NR>1 && $7!=0 {print $NF}' jobs.tsv # command lines of failed jobs
10.0.1.11 up 3 days, 2 hours 10.0.1.11 active 10.0.1.12 up 3 days, 2 hours 10.0.1.12 active ssh: connect to host 10.0.3.31 port 22: Connection timed out failed jobs=1
The first time parallel runs, it prints a citation notice; after an interactive run parallel --citation , it no longer prompts. In scripts / CI, the notice goes to stderr and does not affect results. :::: means reading arguments from a file,::: means passing arguments directly.
max=4; pids=(); fail=0
for host in "${hosts[@]}"; do
ssh -n -o BatchMode=yes -o ConnectTimeout=5 "$host" uptime >"out/$host.log" 2>&1 &
pids+=($!)
while (( $(jobs -rp | wc -l) >= max )); do
wait -n || ((++fail)) # Bash 4.3+: wait for any one to finish
done
done
for p in "${pids[@]}"; do wait "$p" 2>/dev/null || ((++fail)); done
echo "fail=$fail"
This approach is weak at tracking “who failed” (wait -n an already reaped PID, if you wait on it again, wait returns 127, which may double-count); for accurate reporting, use Bash 5.1+'s wait -n -p pid to record PIDs, or just use xargs / parallel.
Zero cost: use mockapi to simulate the hosts' “/healthz”, and use localhost to simulate an SSH target (optional).
mkdir -p ~/bashlab/m3 && cd ~/bashlab/m3
jq -r '.[].name' ~/bashlab/data/inventory.json 2>/dev/null | head -6 > names.txt || true
[[ -s names.txt ]] || printf '%s\n' web-01 web-02 api-01 db-01 cache-01 "batch 01" > names.txt
i=0
while IFS= read -r n; do
case $((i++ % 4)) in
2) url="http://127.0.0.1:8000/status/503" ;;
3) url="http://127.0.0.1:9/healthz" ;;
*) url="http://127.0.0.1:8000/slow?sec=1" ;;
esac
printf '%s\t%s\n' "$n" "$url"
done < names.txt > targets.tsv
cat targets.tsvtime while IFS=$'\t' read -r n url; do curl -fsS -o /dev/null --max-time 3 "$url" && echo "OK $n" || echo "FAIL $n" done < targets.tsv
Roughly equal to the sum of each task's duration (each slow one 1 second).
rm -rf results && mkdir results
check() { # check results-dir name URL
local R=$1 n=$2 url=$3 code rc=0
code=$(curl -sS -o /dev/null -w '%{http_code}' --max-time 3 "$url" 2>"$R/$n.err") || rc=$?
printf '%s\t%s\t%s\n' "$n" "$code" "$rc" > "$R/$n.tsv"
[[ $rc == 0 && $code == 200 ]]
}
export -f check
time (tr '\t\n' '\0\0' < targets.tsv | xargs -0 -n 2 -P 4 bash -c 'check "$1" "$2" "$3"' _ results)
echo "xargs rc=$?"
cat results/*.tsv | sort | column -t -s $'\t'
real 0m1.0xs xargs rc=123 api-01 503 0 batch 01 200 0 cache-01 200 0 db-01 000 7 web-01 200 0 web-02 200 0
awk -F'\t' '$2!=200 || $3!=0 {bad++; print "FAIL", $1, "http="$2, "curl_rc="$3} END {exit bad>0}' results/*.tsv
echo "summary rc=$?"printf '%s\n' localhost localhost 127.0.0.1 > ssh-hosts.txt
xargs -P 3 -I{} ssh -n -o BatchMode=yes -o ConnectTimeout=5 {} 'echo "$(hostname) $(date +%T)"' < ssh-hosts.txtrm -rf ~/bashlab/m3; if you enabled sshd for this lab and no longer need it: sudo systemctl disable --now ssh.Problem: The weekly TLS certificate expiry check script calls while read inside ssh "$h" openssl x509 …, and for three years it has only checked the first host on the list. One edge server's certificate expired and caused an outage. Fix:ssh -n; at the end, the script prints “checked N hosts / M in inventory” and raises an alert if the numbers differ. Limitations: This kind of “silently skipped” failure is hard to catch in testing, so you must rely on count verification.
Problem: Running 800 hosts through one jump host (ProxyJump) with xargs -P 0 ssh …, the jump host's sshd defaults to MaxStartups 10:30:100, so many connections are randomly dropped during authentication, and the script reports 300 hosts as “unreachable”. Fix: Set concurrency to 20; enable SSH connection multiplexing (ControlMaster auto,ControlPersist 5m); for failed tasks, use parallel --retries 2 to retry. Limitations: The control socket directory for connection multiplexing requires strict permissions (for example ~/.ssh/cm-%C).
Problem: The script that restarts services in batches failed to restart all 50 hosts when the new config had an error. Fix:parallel -j 5 --halt soon,fail=2: stop dispatching new tasks after 2 failures; a better approach is Ansible's serial + max_fail_percentage, or run it on one canary host first. Limitations:--halt Tasks already run are not rolled back; you need to design rollback yourself (see Module 4).
Cause: The ssh inside the loop body (or docker exec -i,mysql etc.) read the loop's stdin.
bash -x ./batch.sh 2>&1 | grep -c '+ ssh'
Fix:ssh -n or </dev/null; or read the loop from fd 3: while read -r h <&3; do …; done 3< hosts.txt.
Cause: The host is being connected to for the first time, or its host key has changed; without BatchMode , it waits for interactive input.
ssh-keygen -F web-01; ssh -o BatchMode=yes web-01 true; echo "rc=$?"
Fix: New host: -o StrictHostKeyChecking=accept-new or collect the key in advance with ssh-keyscan and verify the fingerprint; for a changed key, after confirming the host was reinstalled, run ssh-keygen -R web-01. Do not use StrictHostKeyChecking=no + UserKnownHostsFile=/dev/null.
Cause: A downstream command (such as head) closed the pipe early, so the child process received SIGPIPE; or multiple parallel tasks wrote directly to the same stdout.
… | xargs -P 4 … > all.log # lines may interleave
Fix: Each task writes its own file, and you merge them at the end; or use GNU parallel (it groups output by job by default,--line-buffer keeping each line intact).
Cause: You did not set ConnectTimeout, so the system TCP connection timeout applies (Linux default retransmission is about 2 minutes).
Fix:-o ConnectTimeout=5; for command run time, use timeout 60 ssh … (ConnectTimeout only governs the connection phase).
Cause: xargs starts a new process, which cannot see the functions in the current shell.
Fix:export -f run_one then use bash -c 'run_one "$@"' _; GNU parallel also needs export -f, or use env_parallel.
hosts.txt on each host listed in uptime, with no interactive prompts, a 5-second connect timeout, and a 30-second total timeout per host.xargs -P 5 -I{} timeout 30 ssh -n -o BatchMode=yes -o ConnectTimeout=5 {} uptime < hosts.txtparallel -j 5 --tag --timeout 30 --joblog jobs.tsv ssh -n -o BatchMode=yes -o ConnectTimeout=5 {} uptime :::: hosts.txtparallel -j 50 ssh {} 'sed -i … && systemctl restart app'. What would you recommend?This is a high-risk, state-changing batch operation: ① no dry run or idempotency (re-running sed may replace a second time); ② 50 concurrent restarts could cause capacity to drop sharply; ③ no rollback after failure. Recommendation: prefer Ansible (lineinfile/template idempotent,--check --diff dry run,serial: 10% batching,max_fail_percentage circuit breakers, handlers that restart only on change). If you must use Shell: first run it on 1 canary host and verify the health check; parallel -j 10 --halt soon,fail=1 --joblog write commands to be idempotent (check with grep first); run a health check after each host; keep a backup of the old config for rollback.
This courseware cannot directly generate video/MP3, so a storyboard and narration script are provided.
ln -sfn target .current.tmp + mv -Tf .current.tmp current to implement an atomic switch, and explain why rm current; ln -s … rm-then-recreate and -T ln -s without -n mv are both wrong (this module has measured data).flock), version validation, and old-version cleanup (keep N versions and never delete current).~/bashlab/deploy/ ├── releases/ │ ├── 20261117T070539Z/ ← v1.0.0 (complete, read-only release directory) │ ├── 20261117T070540Z/ ← v1.1.0 │ └── 20261117T070541Z/ ← v1.2.0 (health check failed; kept for troubleshooting) ├── current -> releases/20261117T070540Z ← services access code only through this ├── shared/ ← shared across versions: logs, uploads, .env (linked into releases with symlinks as needed) └── .deploy.lock ← deployment lock (this module's standalone script; opsctl v0.3 uses util::lock → ~/bashlab/opsctl/var/lock/deploy.lock)
The web server / systemd unit only references the current path (for example WorkingDirectory=/srv/app/current, nginx root /srv/app/current/public;). Deployment = prepare a new directory and repoint one symlink. Capistrano, Deployer and other tools have used exactly this pattern for years.
tar -x extract directly into the running directory / rsync overwrite): during extraction the service can read a mix of old and new files; a mid-way failure leaves a half-finished version, and rollback means redeploying the old package.rm current && ln -s new current): between the two system calls, current the path does not exist, so requests get 404 / 500. In this module's test, we looped the switch while sending 400 concurrent requests, and 132 requests got 404.rename(2) guarantees that when the new path already exists, it is atomically replaced—at any moment, access to current, either sees the old target or the new one, and never “does not exist”. The same test: 400 requests all returned 200.mkdir releases/$ts + tar -xzf package -C releases/$ts: the new version is fully written to disk (the service cannot see it).version.txt and other key files; optionally run releases/$ts/bin/check.ln -sfn releases/$ts .current.tmp Switch: symlink(2) in the temp name, create a new link (-n-n: if .current.tmp already exists and points to a directory, do not follow into it)mv -Tf .current.tmp current: rename(2) atomic replacement. -T (--no-target-directory) is critical: current current is a symlink pointing to a directory, so without -T , mv treats it as a target directory, moving .current.tmp inside the old release (verified: current still points to the old version, and the old directory gained an extra .tmp2).| Approach | Atomic switch? | Rollback speed | Notes |
|---|---|---|---|
| In-place overwrite (tar / rsync into the running directory) | No | Slow (redeploy) | Simplest, but also the most dangerous |
rm + ln -s | No (has a window) | Fast | Measured: 33% of requests got 404 |
ln -sfn Temp name + mv -T | Yes | Seconds | Used in this lesson |
| Blue-green (two sets of instances + load balancer switch) | Yes (at the LB layer) | Seconds | Requires double the resources; see the CI/CD and K8s courses |
| Container rolling update (K8s Deployment) | Pod by pod | kubectl rollout undo | Handled by the platform; see the Kubernetes course |
Suitable for “file-based” releases on a single machine or a small number of hosts: static sites, PHP / Python / Node application directories, config bundles, binary tools. Limitations: ① long-running processes that already have old files open won't switch automatically; they need a systemctl reload / restart (for example, gunicorn's HUP), or the app reopens files via the path on every request; ② database migrations cannot be rolled back with a symlink, so migrations must be backward-compatible (expand first, contract later); ③ if a process's working directory is current resolved to the real directory, it stays in the old directory after the switch.
ln -sfn new current a single command is atomic”—its semantics are “delete the existing target, then create”; across implementations / versions it may be two steps (unlink + symlink) with a window. Do not rely on this; explicitly use a temp name + mv -T. ② “mv -f tmp current is enough”—when current points to a directory, it moves tmp into that directory. ③ “Running the health check before the switch is enough”—the new version receives no traffic before the switch at all; do a “pre-check” (files, config syntax) before the switch and a “health check” after it; you need both. ④ “Rolling back is just redeploying the old package”—that is a redeploy, which is slow and can fail; a symlink rollback needs only one rename. ⑤ On macOS, the BSD mv has no -T, use mv -h (does not follow the target symlink) or Homebrew gmv -T.Pick a scenario and step through each stage of the deployment script: which system call runs, what changes on the file system, and which version an incoming request sees at that moment. The terminal below shows the script's actual output (measured logs from this module's lab) and the corresponding system calls.
| Command | Purpose | Key points |
|---|---|---|
ln -sfn target link | Create / replace a symlink | -n: if the link already exists and points to a directory, don't follow into it |
mv -Tf source target | Rename and atomically replace | -T: treat the target as a regular file; within the same file system, this is rename(2) |
readlink link / readlink -f | Read the link target / fully resolve | Relative link releases/… easier to relocate as a whole |
flock -n 9 | Acquire the deployment lock without blocking | Two deployments running at once = disaster |
date -u +%Y%m%dT%H%M%SZ | Sortable UTC timestamp | Sorting by name = sorting by time |
systemctl reload app | Make long-running processes load new code | Depends on the app (gunicorn HUP, php-fpm reload) |
mkdir -p releases/a releases/b ln -sfn releases/a current ln -s releases/b .tmp2; mv -f .tmp2 current # wrong: current points to a directory ls -l current; ls -A releases/a ln -s releases/b .tmp3; mv -Tf .tmp3 current # correct ls -l current
lrwxrwxrwx 1 root root 10 Nov 17 02:05 current -> releases/a .tmp2 lrwxrwxrwx 1 root root 10 Nov 17 02:05 current -> releases/b
#!/usr/bin/env bash
# deploy.sh — minimal rollback-capable deployment: releases/<ts> + current symlink
# Usage: deploy.sh <package.tar.gz> [health check URL]
set -Eeuo pipefail
ROOT=${ROOT:-$HOME/bashlab/deploy}
pkg=${1:?Usage: deploy.sh package.tar.gz [URL]}
url=${2:-}
switch() { # atomic switch: create a temp link first, then overwrite current with rename(2)
ln -sfn -- "$1" "$ROOT/.current.tmp"
mv -Tf -- "$ROOT/.current.tmp" "$ROOT/current"
}
healthy() { # up to 3 tries, 2-second timeout each, with 1s and 2s intervals
local i
for i in 1 2 3; do
curl -fsS -o /dev/null --max-time 2 "$url" && return 0
((i < 3)) && sleep "$i"
done
return 1
}
ts=$(date -u +%Y%m%dT%H%M%SZ)
rel="releases/$ts"
mkdir -p -- "$ROOT/$rel"
tar -xzf "$pkg" -C "$ROOT/$rel"
[[ -f $ROOT/$rel/version.txt ]] || { echo "package is missing version.txt" >&2; rm -rf -- "${ROOT:?}/$rel"; exit 1; }
prev=$(readlink -- "$ROOT/current" 2>/dev/null || true)
switch "$rel"
echo "switched: current -> $rel (prev: ${prev:-none}, version $(<"$ROOT/$rel/version.txt"))"
if [[ -n $url ]] && ! healthy; then
if [[ -n $prev ]]; then
switch "$prev"
echo "health check FAILED, rolled back: current -> $prev" >&2
else
echo "health check FAILED, nothing to roll back to" >&2
fi
exit 1
fi
echo "deploy OK: $rel"
Key points: ① ! healthy is in a conditional context,healthy failures inside it do not trigger set -e; ② healthy the loop's last ((i < 3)) evaluates to false,&& a failing non-final command in a list does not trigger errexit; ③ ${ROOT:?} prevents ROOT from being empty when rm -rf /releases/…; ④ relative links releases/$ts let the whole deployment directory be relocated / mounted elsewhere. The production version (locks, cleanup, logs, manual rollback) is in Module 8's lib/cmd_deploy.sh.
# Reference current in the systemd unit (the path is resolved when the process starts) # WorkingDirectory=/srv/myapp/current # ExecStart=/srv/myapp/current/venv/bin/gunicorn app:app # ExecReload=/bin/kill -HUP $MAINPID switch "releases/$ts" && sudo systemctl reload-or-restart myapp.service
On receiving HUP, gunicorn reloads its config and starts new workers (new workers import code from the new path; if using preload_app a full restart is required). Check your application server's docs for details. This lesson's lab uses python3 -m http.server -d current: it opens files by path on every request, so the switch takes effect immediately (verified).
Zero cost: the deployment target is ~/bashlab/deploy, served by Python's built-in http.server.
healthz, simulating a “bad version”):
mkdir -p ~/bashlab/m4/build && cd ~/bashlab/m4 for v in 1.0.0 1.1.0 1.2.0; do d=build/$v; mkdir -p "$d" echo "$v" > "$d/version.txt" echo "<h1>myapp $v</h1>" > "$d/index.html" [[ $v != 1.2.0 ]] && echo ok > "$d/healthz" tar -czf "app-$v.tar.gz" -C "$d" . done ls *.tar.gz
app-1.0.0.tar.gz app-1.1.0.tar.gz app-1.2.0.tar.gz
deploy.sh and save it to ~/bashlab/m4/deploy.sh, then:
chmod +x deploy.sh mkdir -p ~/bashlab/deploy python3 -m http.server 8080 --bind 127.0.0.1 -d ~/bashlab/deploy/current >/dev/null 2>&1 & echo $! > http.pid
At this point current does not exist yet, so requests return 404 — exactly the state before the first deployment.
./deploy.sh app-1.0.0.tar.gz http://127.0.0.1:8080/healthz; echo "rc=$?"; sleep 1 ./deploy.sh app-1.1.0.tar.gz http://127.0.0.1:8080/healthz; echo "rc=$?" curl -s http://127.0.0.1:8080/version.txt
switched: current -> releases/20261117T070539Z (prev: none, version 1.0.0) deploy OK: releases/20261117T070539Z rc=0 switched: current -> releases/20261117T070540Z (prev: releases/20261117T070539Z, version 1.1.0) deploy OK: releases/20261117T070540Z rc=0 1.1.0
sleep 1: timestamps are precise to the second, so two deployments within the same second will collide (Module 8's version detects this and reports an error).
./deploy.sh app-1.2.0.tar.gz http://127.0.0.1:8080/healthz; echo "rc=$?" curl -s http://127.0.0.1:8080/version.txt ls -l ~/bashlab/deploy; ls ~/bashlab/deploy/releases
switched: current -> releases/20261117T070541Z (prev: releases/20261117T070540Z, version 1.2.0) health check FAILED, rolled back: current -> releases/20261117T070540Z rc=1 1.1.0 lrwxrwxrwx current -> releases/20261117T070540Z drwxr-xr-x releases 20261117T070539Z 20261117T070540Z 20261117T070541Z
The bad version's directory is kept for troubleshooting (“why is there no healthz?”). Module 8's cleanup logic will delete it by the retention count in later deployments.
cd ~/bashlab/deploy
mapfile -t R < <(ls releases | head -2)
( for i in $(seq 400); do curl -s -o /dev/null -w '%{http_code}\n' http://127.0.0.1:8080/version.txt; done | sort | uniq -c ) &
for i in $(seq 200); do
for r in "${R[@]}"; do ln -sfn "releases/$r" .t; mv -Tf .t current; done
done; wait
echo "--- control group: rm + ln"
( for i in $(seq 400); do curl -s -o /dev/null -w '%{http_code}\n' http://127.0.0.1:8080/version.txt; done | sort | uniq -c ) &
for i in $(seq 300); do rm -f current; ln -s "releases/${R[0]}" current; done; wait
ln -sfn "releases/${R[1]}" .t && mv -Tf .t current # restore to v1.1.0
400 200
--- control group: rm + ln
268 200
132 404kill "$(cat ~/bashlab/m4/http.pid)" rm -rf ~/bashlab/deploy # Module 8 redeploys; keep the packages under ~/bashlab/m4
Problem: A PHP site got 502s for a few seconds on every deployment: the script first rm -rf /var/www/app then git clone. Fix: Switched to releases/ + current; nginx root points to root /var/www/app/current/public;, and php-fpm uses $realpath_root to pass the script path (avoids OPcache caching the old symlink path); after switching, systemctl reload php-fpm. Limitations: OPcache / application-level caches need to be cleared separately or reloaded.
Problem: The v2 migration dropped a column; after the health check failed, the script switched current back to v1, and v1 errored when reading that column, widening the outage. Fix:“Expand first, contract later” (expand/contract): v2 only adds columns and remains compatible with the old code; v3 drops the old column only after v2 is confirmed stable; the deployment script treats the “migration” as a separate, approvable step. Limitations: Symlink rollback only covers code and static files.
Problem: More than ten deployments a day with no cleanup; releases filled the disk, so the next deployment tar failed, and the script did not set -e, and switched to a half-extracted directory. Fix: Strict mode; verify key files after extraction; keep the most recent 5 releases and never delete current or the previous version; check free space before deploying (df --output=avail). Limitations: The cleanup logic itself also needs testing (Module 8 / bats from Lesson 7).
Cause: Used mv -f instead of mv -Tf; current is a symlink to a directory, so it was treated as the target directory.
ls -lA "$(readlink -f current)" | grep current.tmp
Fix:mv -Tf (GNU); on macOS, use mv -h or gmv -T; delete the file that was moved in by mistake.
Cause: Running directly against current ln -sf without -n, ln followed the symlink to a directory and created the link inside that directory.
Fix: Always use ln -sfn, and on the temp name, then run mv -T.
Cause: A long-running process resolved current at startup (working directory or already-imported modules), so switching the link has no effect on it; or CDN / browser caching.
readlink /proc/$(systemctl show -p MainPID --value myapp)/cwd
Fix: Reload / restart the service after switching; have the health check return the version number (/version), and the script compares “expected version == actual version”.
Cause: Concurrent deployments. Without a lock, two scripts interleave, the one that finishes last “wins”, and the health check may be checking the other deployment's version.
Fix: In the standalone script, use exec 8>"$ROOT/.deploy.lock"; flock -n 8 || exit 1; in opsctl, use util::lock deploy (Lesson 4); in CI, also use concurrency groups (GitHub Actions concurrency:, GitLab resource_group:, see Module 7).
/srv/app/current to releases/20261117T120000Z.cd /srv/app ln -sfn releases/20261117T120000Z .current.tmp mv -Tf .current.tmp current
cur=$(basename "$(readlink current)") ls -1 releases | sort -r | tail -n +6 | grep -vxF "$cur"
/healthz, which occasionally fails right after a new version starts and triggers a rollback (“false rollback”). How would you improve it?① After switching, wait for the service to become ready (readiness), e.g. probe every 1–2 seconds for up to 30 seconds, with exponential backoff and an overall time cap (this lesson's cmd::health -r); ② distinguish liveness and readiness in the health endpoint, and check dependencies (database, cache); ③ compare the returned version number to prevent “an old process answering the health check”; ④ require N consecutive successes before passing, to avoid a lucky pass; ⑤ log each probe's status code and duration, and write them to the logs / CI summary on rollback.
No verified video found that specifically covers “atomic symlink switch deployments”. The following is related background video (title and channel verified via YouTube oEmbed):
This courseware cannot directly generate video/MP3, so a storyboard and narration script are provided.
rm -rf app; tar -x, while the request stream shows red 502s..part a temp file, and after verification, move it mv to the final name; use trap … EXIT to clean up failure leftovers.sha256 checksums; run a restore drill (extract into a temp directory + diff -r).sort -z -r | tail -z -n +N) and by age (find -mtime +N), and understand the GFS (grandfather-father-son) scheme.flock -n to prevent two backups from running at the same time; correctly handle filenames containing spaces, newlines, or a leading dash.find -print0 from Lesson 5. Priority:★★★★☆Select source → lock → pack and compress into a temp file → verify the archive is readable → atomically rename to the final file with a UTC timestamp → generate checksum → (optional) copy off-site → rotate and delete expired backups → release lock → output the result and express success or failure with the exit code.
tar -czf final.tar.gz leaves a truncated file with a “normal” name, and rotation logic will then delete a good older backup because of it.ls -t | tail -n +8 | xargs rm hits a filename with spaces and deletes the wrong file; or find /backups -mtime +7 -delete once backups have stopped for 7 days,it deletes every backup.date -u +%Y%m%dT%H%M%SZ— UTC avoids duplicate names or misordering caused by daylight saving time; lexical order = time order, so rotation only needs to sort by name.tar -C parent-dir -czf … -- dir-name, so restores never write to absolute paths; -- prevents names starting with - from being treated as options.mktemp "$dest/.name.XXXXXX.part", ensuring mv is a rename(2) within the same file system (a cross-file-system mv degrades to “copy + delete”, which is not atomic).tar -tzf check that the archive is readable; sha256sum write .sha256, and after copying off-site, use sha256sum -c to verify the transfer is complete.| Rotation policy | Implementation | Pros | Risks |
|---|---|---|---|
| By count (keep the newest N) | find … -print0 | sort -z -r | tail -z -n +$((N+1)) | Even if backups stop, it won't delete everything | Coverage span changes when frequency changes |
| By age (delete backups older than N days) | find … -mtime +N -delete | Simple and intuitive | Deletes everything if backups fail for a long time; -mtime the rounding rules are easy to misread |
| GFS (7 daily + 4 weekly + 12 monthly) | Classify by date, then keep each class by count | Long time span, controllable count | Complex logic; consider restic / borg's forget --keep-daily … |
| Object storage lifecycle | S3 Lifecycle / Azure Blob lifecycle management | Run by the platform, no script needed | Requires a cloud account; watch minimum storage duration charges |
Suitable for: config directories, small data directories, export files (pg_dump 's output), log archives. Live database files should not be tarred directly (needs the database's own consistent backup tool or snapshots); for large-scale, deduplicated, encrypted, or incremental backups, use restic, BorgBackup, or your cloud provider's backup service.
-mtime +7 means 7 days ago”—find rounds time down to whole 24-hour periods,+7 means “at least 8 full days ago”. ③ “ls | tail | xargs rm is enough”—filenames containing spaces or newlines make it delete the wrong file; use NUL separation. ④ “Gzipping makes it safe”—compression is not encryption; backups that contain keys should be age / gpg encrypted before they leave the host.Simulates one backup per day at 02:00 starting 2026-10-01 for 60 days; you can make the backups on days 41–50 “fail” (e.g. disk full). Observe which backups each of the three policies keeps at the end of day 60. Green = kept, grey = deleted, red = that day's backup failed (no file).
| Command | Purpose | Key points |
|---|---|---|
tar -C dir -czf out.tar.gz -- name | Archive with relative paths | --one-file-system,--exclude=PATTERN; zstd: --zstd |
tar -tzf f / tar -xzf f -C dir | List / extract | Restore drill: extract to a temp directory |
sha256sum f > f.sha256 / sha256sum -c | Checksum | Generated in the backup directory; filenames are relative paths |
find d -maxdepth 1 -name 'x-*' -print0 | List backups | Use with sort -z,tail -z,read -d '' together |
find d -name 'x-*' -mtime +7 -delete | Delete by age in days | First use -print to dry-run |
flock -n 9 | Prevent concurrent runs | exec 9>lockfile Open fd |
rsync -a --partial src/ host:dst/ | Off-site copy | On the remote end, then sha256sum -c |
#!/usr/bin/env bash
# backup.sh — archive directory + checksum + rotation
# Usage: backup.sh <source-dir> [dest-dir] [keep-count]
set -Eeuo pipefail
src=${1:?Usage: backup.sh source-dir [dest-dir] [keep-count]}
dest=${2:-$HOME/bashlab/backups}
keep=${3:-7}
[[ -d $src ]] || { echo "Not a directory: $src" >&2; exit 2; }
src=$(cd -- "$src" && pwd)
name=$(basename -- "$src")
mkdir -p -- "$dest"
exec 9>"$dest/.backup.lock"
flock -n 9 || { echo "Another backup is already running" >&2; exit 1; }
ts=$(date -u +%Y%m%dT%H%M%SZ)
final="$dest/$name-$ts.tar.gz"
tmp=$(mktemp "$dest/.$name.XXXXXX.part")
trap 'rm -f -- "$tmp"' EXIT
tar -C "$(dirname -- "$src")" -czf "$tmp" -- "$name"
tar -tzf "$tmp" >/dev/null
mv -f -- "$tmp" "$final"
(cd -- "$dest" && sha256sum -- "${final##*/}" >"${final##*/}.sha256")
echo "created $final"
# Rotation: names contain a UTC timestamp, so reverse order = newest to oldest; delete the keep+1th and older
while IFS= read -r -d '' old; do
rm -f -- "$old" "$old.sha256"
echo "rotated $old"
done < <(find "$dest" -maxdepth 1 -type f -name "$name-*.tar.gz" -print0 | sort -z -r | tail -z -n +"$((keep + 1))")
Note trap 'rm -f -- "$tmp"' EXIT Use single quotes: variables expand only when the trap fires; on success mv , after which $tmp no longer exists,rm -f silently harmless. sort -z,tail -z is a GNU extension (on macOS, install the Homebrew coreutils version of gsort/gtail).
for i in 1 2 3 4; do ./backup.sh ~/bashlab/data ~/bashlab/backups 3; sleep 1.1; done ls -1 ~/bashlab/backups (cd ~/bashlab/backups && sha256sum -c ./*.sha256)
created ~/bashlab/backups/data-20261117T070823Z.tar.gz created ~/bashlab/backups/data-20261117T070824Z.tar.gz created ~/bashlab/backups/data-20261117T070825Z.tar.gz created ~/bashlab/backups/data-20261117T070826Z.tar.gz rotated ~/bashlab/backups/data-20261117T070823Z.tar.gz data-20261117T070824Z.tar.gz data-20261117T070824Z.tar.gz.sha256 data-20261117T070825Z.tar.gz data-20261117T070825Z.tar.gz.sha256 data-20261117T070826Z.tar.gz data-20261117T070826Z.tar.gz.sha256 data-20261117T070824Z.tar.gz: OK data-20261117T070825Z.tar.gz: OK data-20261117T070826Z.tar.gz: OK
latest=$(find ~/bashlab/backups -maxdepth 1 -name 'data-*.tar.gz' | sort | tail -1)
r=$(mktemp -d); tar -xzf "$latest" -C "$r"
diff -r ~/bashlab/data "$r/data" && echo "restore OK: identical"
tar -tzf "$latest" | head -5
echo garbage >> "$latest" # simulate corruption
(cd ~/bashlab/backups && sha256sum -c "${latest##*/}.sha256"); echo "rc=$?"
restore OK: identical data/ data/files/ data/files/new\nline data/files/my report.txt data/files/-rf data-20261117T070826Z.tar.gz: FAILED sha256sum: WARNING: 1 computed checksum did NOT match rc=1
tar -t Newlines in filenames are displayed as \n; the archive stores the real filename, so after restore it is diff -r identical.
( exec 9>~/bashlab/backups/.backup.lock; flock 9; sleep 3 ) & # simulate a backup that is running sleep 0.5; ./backup.sh ~/bashlab/data ~/bashlab/backups 3; echo "rc=$?"; wait touch -d '10 days ago' ~/bashlab/backups/data-20261101T000000Z.tar.gz find ~/bashlab/backups -maxdepth 1 -name 'data-*.tar.gz' -mtime +7 -print # dry-run first, then switch to -delete
Another backup is already running rc=1 ~/bashlab/backups/data-20261101T000000Z.tar.gz
# another host (zero cost: can be another directory on localhost)
rsync -a --partial ~/bashlab/backups/ backup-host:/srv/backups/$(hostname)/
ssh -n backup-host "cd /srv/backups/$(hostname) && sha256sum -c --quiet ./*.sha256"
# cloud (incurs small storage costs; not run by default in this course)
# az storage blob upload --account-name <acct> -c backups -f "$latest" -n "$(hostname)/${latest##*/}" --auth-mode login
# aws s3 cp "$latest" "s3://<bucket>/$(hostname)/" --storage-class STANDARD_IA
make-data.sh, which includes the “weird name” file):
ls ~/bashlab/data ~/bashlab/data/files | head mkdir -p ~/bashlab/m5 && cd ~/bashlab/m5
backup.sh and save it as ~/bashlab/m5/backup.sh and chmod +x; first bash -n backup.sh do a syntax check..part:
install -m 000 /dev/null ~/bashlab/data/secret.bin # unreadable to normal users (no effect as root) ./backup.sh ~/bashlab/data ~/bashlab/backups 3; echo "rc=$?" ls -A ~/bashlab/backups | grep part || echo "No leftover .part ✓" rm -f ~/bashlab/data/secret.bin
tar: data/secret.bin: Cannot open: Permission denied tar: Exiting with failure status due to previous errors rc=2 No leftover .part ✓
GNU tar exits with status 2 (fatal error) when it hits an unreadable file; set -e this makes the script exit immediately, the EXIT trap deletes the temp file, rotation does not run, and the old backups stay intact.
flock ~/bashlab/backups/.backup.lock sleep 30, then run a backup in a second terminal and confirm you get “Another backup is already running” and rc=1.diff -r; add the drill commands to ~/bashlab/m5/restore-drill.sh, as part of a scheduled job (Module 6).rm -rf ~/bashlab/backups/.backup.lock (The lock file can stay; it does not affect the next run). The backup files are kept for Module 6.Problem: The backup job failed 10 days in a row due to expired credentials, with no alert; the find /backups -mtime +7 -delete ran as usual every day, and from day 8 onward it gradually deleted all backups. Fix:① Run rotation only after “this backup succeeds”, within the same script; ② switch to keeping a fixed number of copies; ③ monitor the “age of the latest backup” (alert if older than 26 hours) rather than only whether the job failed. Limitation: Keep-by-count needs N adjusted whenever the schedule changes.
Problem: The tar archive used absolute paths and was extracted with BSD tar on macOS, so permissions and extended attributes were lost. In another incident, a backup file was truncated by a sync tool and never verified. Fix: Archive with relative paths; run an automated restore drill every week (extract to a temp directory + spot-check checksums + application-level checks, such as pg_restore --list); every copy ships with .sha256. Limitation: Restore drills consume I/O, so run them during off-peak hours.
Problem: The PostgreSQL data directory was tarred directly while the database was running; after restore, the database would not start (inconsistent files). Fix: Use pg_dump / pg_basebackup or a filesystem / cloud disk snapshot (freeze I/O first); the backup script only handles “call a consistency tool, archive, verify and rotate”. Limitation: Large databases should use incremental / PITR approaches, which are beyond the scope of shell scripts.
Cause: Archived with absolute paths; GNU tar automatically strips the leading / (this is a safety measure, not an error).
Fix:tar -C /parent -czf out.tar.gz -- dirname, so the archive contains clean relative paths.
Cause: The file was modified during archiving (logs, database files). GNU tar returns 1 for this (“some files differ”), so with set -e , the script exits.
tar … ; echo "tar rc=$?" # 0 success · 1 a file changed while being read · 2 fatal error
Fix: Snapshot or export volatile data first; if acceptable for the business, explicitly allow 1: tar … || [[ $? -eq 1 ]], and log a warning.
Cause: The file was corrupted or truncated during copy / storage, or the checksum file refers to a different version.
Fix: Restore from another copy; check the transfer tool (use rsync --checksum or the object store's MD5/CRC checks); alert instead of silently skipping.
Cause: The destination directory is not writable or is full.
df -h "$dest"; df -i "$dest"; ls -ld "$dest"
Fix: Check free space before backing up (for example, compare avail=$(df --output=avail -k "$dest" | tail -1) with the source size du -sk ). Rotate-then-backup should only be considered when there is a real space problem and at least 2 copies are kept.
/backups , keep only the newest 5 app-*.tar.gz (file names may contain spaces), and delete the rest along with their .sha256 files.find /backups -maxdepth 1 -type f -name 'app-*.tar.gz' -print0 | sort -z -r | tail -z -n +6 | while IFS= read -r -d '' f; do rm -f -- "$f" "$f.sha256"; done
[[ -n $(find /backups -maxdepth 1 -name 'app-*.tar.gz' -mmin -$((26*60)) -print -quit) ]] || { echo "Latest backup is too old" >&2; exit 1; }① Check the mount before writing: mountpoint -q /mnt/backup || { echo "Not mounted"; exit 1; }; ② or place a sentinel file on the mount point (.backup-target), write only when it exists; ③ for a systemd timer, use RequiresMountsFor=/mnt/backup (Module 6); ④ local partition monitoring and quotas; ⑤ alert on backup failures (non-zero exit code + OnFailure).
-C,--one-file-system)-mtime rounding rules) · sha256sum(1)This lesson cannot directly generate a video/MP3, so a storyboard and narration script are provided instead.
% escaping,MAILTO,CRON_TZ), explain three pitfalls of the cron environment: a minimal PATH,/bin/sh, and no terminal..service (Type=oneshot) + .timer (OnCalendar,Persistent,RandomizedDelaySec) use systemd-analyze calendar to validate the expression.systemctl --user + loginctl enable-linger) to schedule opsctl without requiring root.cron (on Debian/Ubuntu it is a derivative of Vixie cron cron, on RHEL-family systems it is cronie): the daemon checks the crontab every minute and runs due jobs through /bin/sh -c , executing command lines; output is sent by local mail to MAILTO (lost if there is no MTA). systemd timer: .timer The timer unit, when its time comes,starts the same-named (or Unit= specified) .service unit; the service runs in a clean environment managed by systemd, with output going to journald.
PATH usually contains only /usr/bin:/bin, so it cannot find /usr/local/bin/opsctl,~/.local/bin/az; it does not load ~/.bashrc; it uses sh rather than Bash.% means a newline,date +%F so it must be written as date +\%F.Persistent=true runs the missed job once after boot.OnFailure= trigger a notification unit, and failures are visible in systemctl --failed .# crontab: min hour day month weekday command # ┌──────── minute (0-59) # │ ┌────── hour (0-23) # │ │ ┌──── day of month (1-31) # │ │ │ ┌── month (1-12) # │ │ │ │ ┌ day of week (0-7, 0 and 7 are Sunday) 0 2 * * * /home/lab/bashlab/opsctl/bin/opsctl backup /home/lab/bashlab/data */5 * * * * flock -n /tmp/health.lock opsctl health http://127.0.0.1:8080/healthz # systemd OnCalendar: weekday year-month-day hour:minute:second OnCalendar=*-*-* 02:00:00 # every day at 02:00 (daily means 00:00) OnCalendar=Mon..Fri *-*-* 09:30 # weekdays 09:30 OnCalendar=*:0/5 # every 5 minutes OnCalendar=*-*-01 03:00 # 1st of every month at 03:00
| Dimension | cron | systemd timer |
|---|---|---|
| Configuration | One crontab line | .service + .timer Two files |
| Shell / environment | /bin/sh, minimal PATH, variables can be set at the top of the crontab | No shell (ExecStart is exec'd directly) Environment= / EnvironmentFile= |
| Missed jobs | Not run (needs anacron) | Persistent=true Run after boot |
| Overlapping runs | May overlap; needs flock -n | ; a running service is not started again |
| Random jitter | DIY sleep $((RANDOM % 600)) | RandomizedDelaySec= |
| Logs | Mail / redirect yourself | journald: journalctl -u x.service |
| Failure notifications | Relies on mail | OnFailure=,systemctl --failed |
| Dependencies & resources | None | RequiresMountsFor=,After=network-online.target,CPUQuota=,TimeoutStartSec=, sandboxing options |
| Portability | Almost all Unix systems, container images | Only on systemd systems; usually unavailable in containers |
| Validation | (no built-in) | systemd-analyze calendar,systemd-analyze verify,systemctl list-timers |
schedule:, GitLab scheduled pipelines, see Module 7) or a job scheduling platform.OnCalendar=daily is 2 am”—it is actually 00:00 (verified systemd-analyze calendar daily normalized to *-*-* 00:00:00). ② “Enabling the .service makes it run on a schedule”—what needs to be enabled is enable --now the .timer; .service usually has no [Install]. ③ “User timers keep running after I log out”—by default the user instance stops when the last session ends, so you need loginctl enable-linger user. ④ “Just set source ~/.bashrc and it works”—many .bashrc at the top returns right away in a non-interactive shell; set it explicitly in the script or in the crontab PATH.Job: back up every day at 02:00 (may take a long time). Pick a scenario and step through the events on both timelines and the matching real logs.
| Command | Purpose | Key points |
|---|---|---|
crontab -e / -l | Edit / view the current user's crontab | Checks syntax on save |
grep CRON /var/log/syslog / journalctl -u cron | View cron execution log | Only records that it ran, not its output |
systemd-analyze calendar 'expr' | Validate an OnCalendar expression | --iterations=N Shows the next several run times |
systemd-analyze verify x.timer | Statically check unit files | Warns about misspelled keys |
systemctl --user enable --now x.timer | Enable a user timer | Enable the .timer |
systemctl --user list-timers | Next / last trigger times | System-level: drop --user |
systemctl --user start x.service | Run once immediately | most useful for testing |
journalctl --user -u x.service -n 50 | View output | -f Follow |
loginctl enable-linger $USER | Keep the user instance running when the user is logged out | Requires root or polkit permission |
systemd-run --user --on-calendar=… cmd | Transient timer (no file written) | good for one-off experiments |
crontab -e # ---- crontab content below ---- SHELL=/bin/bash PATH=/home/lab/bashlab/opsctl/bin:/usr/local/bin:/usr/bin:/bin MAILTO="" CRON_TZ=UTC # back up daily at 02:00 UTC; prevent overlap; random delay of 0–599 seconds; append output to the log with timestamps 0 2 * * * flock -n /tmp/opsctl-backup.lock bash -c 'sleep $((RANDOM \% 600)); opsctl backup -k 14 "$HOME/bashlab/data"' >> "$HOME/bashlab/logs/backup.log" 2>&1 # health check every 5 minutes; on failure, write to the system log with logger */5 * * * * opsctl health -r 3 http://127.0.0.1:8080/healthz 2>&1 | logger -t opsctl-health
Key points: % Write it as \%; MAILTO="" turn off mail (output is already redirected); CRON_TZ supported by cronie and Debian cron (see man 5 crontab for details); SHELL=/bin/bash let the command line be parsed by Bash. ~/bashlab/logs needs to be created first. Note the second line: after the pipe, cron only sees logger's exit code.
mkdir -p ~/.config/systemd/user ~/bashlab/logs cat > ~/.config/systemd/user/opsctl-backup.service <<'EOF' [Unit] Description=opsctl backup of ~/bashlab/data # when the backup target is on a mount point: RequiresMountsFor=/mnt/backup OnFailure=opsctl-notify@%n.service [Service] Type=oneshot Environment=OPSCTL_BACKUP_KEEP=14 NO_COLOR=1 ExecStart=%h/bashlab/opsctl/bin/opsctl backup -o %h/bashlab/backups %h/bashlab/data TimeoutStartSec=30min Nice=10 IOSchedulingClass=idle EOF cat > ~/.config/systemd/user/opsctl-backup.timer <<'EOF' [Unit] Description=Daily opsctl backup [Timer] OnCalendar=*-*-* 02:00:00 Persistent=true RandomizedDelaySec=10min [Install] WantedBy=timers.target EOF cat > ~/.config/systemd/user/opsctl-notify@.service <<'EOF' [Unit] Description=Notify failure of %i [Service] Type=oneshot ExecStart=/usr/bin/logger -p user.err -t opsctl-notify "unit %i failed" EOF systemd-analyze --user verify ~/.config/systemd/user/opsctl-backup.* systemctl --user daemon-reload systemctl --user enable --now opsctl-backup.timer systemctl --user list-timers opsctl-backup.timer
NEXT LEFT LAST PASSED UNIT ACTIVATES Wed 2026-11-18 02:04:17 UTC 19h left - - opsctl-backup.timer opsctl-backup.service 1 timers listed.
%h is the user home directory specifier,%n is the full unit name,%i is the template instance name (systemd.unit(5)). In production, you can replace opsctl-notify@ with a script that calls a webhook. NEXT The time includes the random delay.
systemd-analyze calendar --iterations=3 '*-*-* 02:00:00' systemd-analyze calendar daily
Normalized form: *-*-* 02:00:00
Next elapse: Wed 2026-11-18 02:00:00 EST
(in UTC): Wed 2026-11-18 07:00:00 UTC
From now: 23h left
Iteration #2: Thu 2026-11-19 02:00:00 EST
(in UTC): Thu 2026-11-19 07:00:00 UTC
From now: 1 day 23h left
Iteration #3: Fri 2026-11-20 02:00:00 EST
(in UTC): Fri 2026-11-20 07:00:00 UTC
From now: 2 days left
Original form: daily
Normalized form: *-*-* 00:00:00
…
OnCalendar uses the system local timezone by default; to fix a timezone, append the timezone name to the expression, for example *-*-* 02:00:00 UTC.
systemctl --user start opsctl-backup.service # run once now (waits in the foreground for the oneshot to finish) systemctl --user status opsctl-backup.service --no-pager journalctl --user -u opsctl-backup.service -n 20 --no-pager loginctl show-user "$USER" -p Linger # only Linger=yes keeps it running after logout
Requires systemd (linuxlab VM; on WSL2, in /etc/wsl.conf the [boot] section, set systemd=true and wsl --shutdown restart). In containers systemd is usually missing, so you can do only the cron part. The opsctl v0.3's backup subcommand is completed in Module 8; finish Module 8 first and come back, or temporarily replace ExecStart with the Module 5's backup.sh.
mkdir -p ~/.config/systemd/user/opsctl-backup.timer.d printf '[Timer]\nOnCalendar=\nOnCalendar=*:0/2\nRandomizedDelaySec=0\n' \ > ~/.config/systemd/user/opsctl-backup.timer.d/lab.conf systemctl --user daemon-reload systemctl --user enable --now opsctl-backup.timer systemctl --user list-timers opsctl-backup.timer --no-pager
In the drop-in, first write an empty OnCalendar= to clear the original value, then set the new value (the reset rule for list-type settings).
journalctl --user -u opsctl-backup.service --since -10min --no-pager | tail ls -1t ~/bashlab/backups | head -4
Nov 17 10:02:00 linuxlab systemd[1234]: Starting opsctl-backup.service - opsctl backup of ~/bashlab/data... Nov 17 10:02:00 linuxlab opsctl[5678]: 2026-11-17T10:02:00+0000 INFO opsctl[5678]: backup created: /home/lab/bashlab/backups/data-20261117T100200Z.tar.gz (4.0K) Nov 17 10:02:00 linuxlab systemd[1234]: Finished opsctl-backup.service - opsctl backup of ~/bashlab/data.
mv ~/bashlab/data ~/bashlab/data.off systemctl --user start opsctl-backup.service; echo "rc=$?" systemctl --user --failed --no-pager journalctl --user -t opsctl-notify -n 3 --no-pager; journalctl -t opsctl-notify -n 3 --no-pager mv ~/bashlab/data.off ~/bashlab/data; systemctl --user reset-failed
opsctl returns usage error 2 for “not a directory”; the service enters the failed state, and OnFailure starts the notification unit (logs written by logger may be in the user or system journal, depending on configuration).
crontab -e Add */2 * * * * env > /tmp/cron-env.txt, and two minutes later cat /tmp/cron-env.txt, compare with the interactive shell's env: how short is PATH?rm ~/.config/systemd/user/opsctl-backup.timer.d/lab.conf systemctl --user daemon-reload # restore to daily at 02:00; if not needed: # systemctl --user disable --now opsctl-backup.timer crontab -l | grep -v cron-env | crontab - # delete the comparison cron line
Problem: To save costs, the dev VMs were powered off at 20:00 and on at 08:00 every night, so the 02:00 cleanup job in cron never ran again. Fix: Switch to a systemd timer + Persistent=true: after boot, if the last trigger was earlier than the scheduled time, it runs once immediately (the timestamp is recorded in /var/lib/systemd/timers/, and user-level units keep it in ~/.local/share/systemd/timers/). Limitation: It catches up only once; it does not replay all missed runs.
Problem: Cron on thousands of hosts all run at 0 * * * * to report metrics; the monitoring backend's CPU maxes out every hour on the hour. Fix: systemd RandomizedDelaySec=15min (random each time) or FixedRandomDelay=true (a fixed random offset per host, more predictable); in cron, compute a fixed offset minute from a hash of the hostname. Limitation: Results arrive more spread out, so alert rules need to account for the delay.
Problem: Backups were written to /etc/crontab and ran as root, so the generated files were owned by root; later a normal user's cleanup script could not delete them and the disk filled up. Fix: Use a user-level timer, or set User=,Group= in a system-level unit; only elevate privileges when truly needed; systemd units can add ProtectSystem=strict,ReadWritePaths= to limit the writable scope. Limitation: Sandbox options need to be tested one by one, to avoid scripts failing on a read-only filesystem.
Cause: cron's PATH does not include the directory where opsctl lives.
* * * * * env > /tmp/cron-env.txt # temporarily add this to see cron's real environment
Fix: Set PATH=… at the top of the crontab, or use an absolute path; the script itself should not depend on the caller's PATH either.
Cause: An unescaped % in crontab is converted to a newline, and everything after it becomes the command's stdin.
Fix:date +\%F; or put complex commands in a script file, so crontab only calls the script.
Cause: Switching users via su / sudo -u does not create a login session, so the user's systemd instance and D-Bus are unavailable.
loginctl show-user "$USER" -p Linger -p State; echo "$XDG_RUNTIME_DIR"
Fix: Use ssh user@host or machinectl shell user@ log in as that user; or sudo -u user XDG_RUNTIME_DIR=/run/user/$(id -u user) systemctl --user …; and loginctl enable-linger.
Cause: Only the .service was enabled; or the .timer was changed without daemon-reload; or the OnCalendar expression is invalid.
systemctl --user list-timers --all; systemd-analyze calendar 'your expression'; systemctl --user cat opsctl-backup.timer
Fix:systemctl --user daemon-reload && systemctl --user enable --now x.timer.
Cause: The previous run hung (for example waiting on the network, a lock, or interactive input), and systemd does not start a second instance.
Fix: Set TimeoutStartSec= (oneshot waits indefinitely by default), give network calls in the script a timeout (Module 1), and check systemctl --user status 's process tree.
/opt/bin/report.sh on weekdays at 18:30, appending output to /var/log/report.log, with the date in the log file name (YYYY-MM-DD).30 18 * * 1-5 /opt/bin/report.sh >> /var/log/report-$(date +\%F).log 2>&1
[Timer] OnCalendar=Sun *-*-* 03:15:00 UTC Persistent=true RandomizedDelaySec=5min # verify: systemd-analyze calendar 'Sun *-*-* 03:15:00 UTC'
① Environment: ExecStart does not go through a shell, so pipes / redirects / % need to be rewritten (using /bin/bash -c or wrap it in a script), and set environment variables with Environment=; ② time zones and expression semantics (in cron, the day-of-month and day-of-week fields are OR-ed, while OnCalendar uses AND); ③ changes in overlap behavior (jobs that relied on running in parallel); ④ whether catch-up of missed runs (Persistent) is expected; ⑤ output moves from mail to journald, and alerts become OnFailure; ⑥ permissions and sandboxing (User=); ⑦ use systemd-analyze calendar to check next trigger times one by one; during migration, do not enable both sides at the same time.
This lesson cannot directly generate a video/MP3, so a storyboard and narration script are provided instead.
journalctl -u shows output; on failure, OnFailure sends a notification.run: no shell specified and shell: bash (bash -e {0} vs bash --noprofile --norc -eo pipefail {0}), and the GitLab rule that “when multiple commands are merged into one line, only the last one is reported”.::add-mask::, masked variables), concurrency (concurrency / resource_group), artifacts and digests ($GITHUB_STEP_SUMMARY,artifacts:).GitHub Actions: each run: step's content is written to a temporary script file, and executed using the template of shell: 's template. In the official docs (Workflow syntax), the templates are: unspecified shell (non-Windows) → bash -e {0}; shell: bash → bash --noprofile --norc -eo pipefail {0}; shell: sh → sh -e {0}. In other words,only when you explicitly write shell: bash is pipefail enabled.. GitLab CI: the Runner runs each item in the script: array in order; any non-zero return fails the job and later commands do not run; if you write several commands as one string (for example, using > folding), only the last result is reported (GitLab docs “Scripts and job logs”).
read, pagers) hang or fail immediately.~/.bashrc, logged-in az / aws sessions, and installed tools are all absent.set -x can print tokens from the command line (the platform masks registered secrets on a best-effort basis, but concatenated or encoded values are not recognized).bin/opsctl,ci/smoke.sh), and the script itself includes set -Eeuo pipefail so it does not depend on CI's default shell options, and local and CI behave the same.shell: bash (GitHub), or use an image that includes Bash (GitLab image: bash:5.3 needs apk add as a dependency).continue-on-error / allow_failure), rather than swallowing errors in the script.| Requirement | GitHub Actions | GitLab CI |
|---|---|---|
| Default shell options | Unspecified: bash -e; shell: bash: -eo pipefail | each script item stops on failure |
| Scheduled runs | on: schedule: - cron: '0 2 * * *' (UTC) | Pipeline schedules in project settings + rules: if: $CI_PIPELINE_SOURCE == "schedule" |
| Manual runs | workflow_dispatch | when: manual / Run pipeline |
| Secrets | ${{ secrets.X }} (automatic masking),echo "::add-mask::$v" | Masked / Protected variables |
| Deploy serialization | concurrency: { group: deploy-prod, cancel-in-progress: false } | resource_group: production |
| Results | $GITHUB_STEP_SUMMARY,actions/upload-artifact@v7,::error:: | artifacts: paths / reports: junit |
| Cloud login (OIDC) | permissions: id-token: write + azure/login@v3 / aws-actions/configure-aws-credentials@v6 | id_tokens: + az login --federated-token / aws sts assume-role-with-web-identity |
Tasks that need code review, approvals, a traceable history, or centralized credential management (deployments, inspection reports, cloud resource cleanup) belong in CI. Tasks that need access to internal network or local resources, run at high frequency (minutes), or must run even when CI is unavailable (local backups, health checks) belong in a host timer (Module 6).
shell: bash . ② “set -x Running it in CI is fine, since secrets are masked”—masking is string replacement of known values; base64 / URL-encoded values, or an Authorization header built by concatenation, are not recognized. ③ “Just rerun it when CI fails”—deploy jobs must be idempotent or reversible (Module 4), otherwise reruns can stack side effects. ④ “schedule uses my local timezone”—GitHub Actions cron runs in UTC (see the official docs), and it may be delayed under heavy load.Choose a platform and a scenario, then step through how the runner executes your script and how the exit code determines the state of the step and the job.
| Syntax | Platform | Purpose |
|---|---|---|
defaults: run: shell: bash | GitHub | Use -eo pipefail |
echo "name=value" >> "$GITHUB_OUTPUT" | GitHub | for step outputs (steps.id.outputs.name) |
echo "### Result" >> "$GITHUB_STEP_SUMMARY" | GitHub | job summary (Markdown) |
echo "::error file=x.sh,line=3::message" | GitHub | annotation (shown in the PR) |
echo "::add-mask::$value" | GitHub | also mask sensitive values generated at runtime |
if: always() / if: failure() | GitHub | Cleanup / failure notification step |
resource_group: production | GitLab | jobs in the same resource group run serially |
artifacts: when: always | GitLab | keep logs even on failure |
CI=true | Both | scripts can use this to disable color / interaction |
name: opsctl
on:
push:
paths: ['opsctl/**', '.github/workflows/opsctl.yml']
schedule:
- cron: '17 2 * * *' # every day at 02:17 UTC (avoids the top-of-the-hour peak)
workflow_dispatch:
permissions:
contents: read
defaults:
run:
shell: bash # → bash --noprofile --norc -eo pipefail {0}
jobs:
smoke:
runs-on: ubuntu-24.04
timeout-minutes: 15
steps:
- uses: actions/checkout@v7
- name: Tools
run: |
bash --version | head -1
curl --version | head -1
command -v shellcheck && shellcheck --version | sed -n 2p || echo "shellcheck not preinstalled"
- name: Lint
run: shellcheck -x opsctl/bin/opsctl opsctl/lib/*.sh
- name: Start mock API
run: |
python3 opsctl/test/mockapi.py 8000 2>mock.log &
for i in {1..20}; do curl -fsS http://127.0.0.1:8000/healthz >/dev/null && break; sleep 0.5; done
- name: Smoke test opsctl
run: |
export PATH="$PWD/opsctl/bin:$PATH"
opsctl version
opsctl health -r 4 "http://127.0.0.1:8000/flaky?fail=2&key=ci-$GITHUB_RUN_ID"
mkdir -p data && echo hello > data/a.txt
opsctl backup -o "$RUNNER_TEMP/backups" -k 2 data
{
echo "### opsctl smoke ✅"
echo '| Check | Result |'
echo '|---|---|'
echo "| health | OK |"
echo "| backup | $(ls "$RUNNER_TEMP/backups" | grep -c 'tar.gz$') copies |"
} >> "$GITHUB_STEP_SUMMARY"
- name: Upload logs
if: always()
uses: actions/upload-artifact@v7
with:
name: opsctl-logs
path: mock.log
Key points: runs-on Pin the version (ubuntu-24.04) to avoid ubuntu-latest tool version changes caused by migration; GitHub-hosted Ubuntu runner images usually preinstall shellcheck and jq (see the software list in actions/runner-images). "$RUNNER_TEMP" is the temp directory for each job. { …; } >> file A single redirect writes a multi-line summary.
cloud-inventory:
runs-on: ubuntu-24.04
permissions:
id-token: write # allows requesting an OIDC token
contents: read
steps:
- uses: azure/login@v3
with:
client-id: ${{ vars.AZURE_CLIENT_ID }}
tenant-id: ${{ vars.AZURE_TENANT_ID }}
subscription-id: ${{ vars.AZURE_SUBSCRIPTION_ID }}
- name: Inventory (read-only)
shell: bash
run: |
az group list --query "[].[name, location]" -o tsv | tee rg.tsv
echo "Resource group count: $(wc -l < rg.tsv)" >> "$GITHUB_STEP_SUMMARY"
# AWS equivalent: aws-actions/configure-aws-credentials@v6 (role-to-assume, aws-region)
For the steps to create the federated credential / IAM OIDC provider, see GitHub course(the Actions and OIDC section). Grant the role only Reader / read-only policies.
stages: [lint, test, deploy]
default:
image: bash:5.3 # official image based on Alpine
before_script:
- apk add --no-cache curl jq python3 coreutils util-linux tar shellcheck
lint:
stage: lint
script:
- shellcheck -x opsctl/bin/opsctl opsctl/lib/*.sh
smoke:
stage: test
script:
- python3 opsctl/test/mockapi.py 8000 2>mock.log &
- for i in $(seq 20); do curl -fsS http://127.0.0.1:8000/healthz >/dev/null && break; sleep 0.5; done
- export PATH="$CI_PROJECT_DIR/opsctl/bin:$PATH"
- opsctl health -r 4 "http://127.0.0.1:8000/flaky?fail=2&key=ci-$CI_JOB_ID"
- mkdir -p data && echo hello > data/a.txt
- opsctl backup -o backups -k 2 data
artifacts:
when: always
paths: [mock.log, backups/]
expire_in: 3 days
rules:
- if: $CI_PIPELINE_SOURCE == "schedule"
- changes: [opsctl/**/*]
deploy:
stage: deploy
resource_group: production # only one deployment runs at a time
script:
- ./ci/deploy.sh # internally calls opsctl deploy; on failure, rolls back automatically and exits 1
rules:
- if: $CI_COMMIT_BRANCH == $CI_DEFAULT_BRANCH
when: manual
Note: commands containing a colon must be quoted as a whole (GitLab docs: YAML treats key: value as a mapping); for … done Inside one script item it counts as one command. Alpine's coreutils / util-linux package provides GNU versions of mv -T,sort -z,flock (BusyBox versions have incomplete options). Package names are as listed in the Alpine repository.
# ci/lib.sh — sourced by CI scripts
ci::group() { [[ ${GITHUB_ACTIONS:-} == true ]] && echo "::group::$*" || echo "== $*"; }
ci::endgroup() { [[ ${GITHUB_ACTIONS:-} == true ]] && echo "::endgroup::" || true; }
ci::error() { [[ ${GITHUB_ACTIONS:-} == true ]] && echo "::error::$*" || echo "ERROR: $*" >&2; }
ci::mask() { [[ ${GITHUB_ACTIONS:-} == true ]] && echo "::add-mask::$1" || true; }
token=$(az account get-access-token --query accessToken -o tsv)
ci::mask "$token" # mask first, before it can appear anywhere in logs
Zero cost: Actions is free for public GitHub repositories; private repositories have a monthly free quota. Without a remote repository you can complete steps 1–3 locally only.
cp ~/bashlab/mock/mockapi.py ~/bashlab/opsctl/test/mockapi.py
~/bashlab/opsctl/test/smoke.sh:
cat > ~/bashlab/opsctl/test/smoke.sh <<'EOF'
#!/usr/bin/env bash
# smoke test shared by local and CI
set -Eeuo pipefail
here=$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd)
port=${SMOKE_PORT:-18000}
work=$(mktemp -d)
python3 "$here/mockapi.py" "$port" 2>"$work/mock.log" &
mock=$!
trap 'kill "$mock" 2>/dev/null || true; rm -rf "$work"' EXIT
for _ in $(seq 20); do curl -fsS "http://127.0.0.1:$port/healthz" >/dev/null 2>&1 && break; sleep 0.3; done
O="$here/../bin/opsctl"
"$O" version
"$O" health -r 4 "http://127.0.0.1:$port/flaky?fail=2&key=smoke-$$"
if "$O" health -r 2 "http://127.0.0.1:$port/status/500"; then
echo "Expected health to fail on 500, but it succeeded" >&2; exit 1
fi
mkdir -p "$work/data" && echo hi > "$work/data/a.txt"
"$O" backup -o "$work/bk" -k 2 "$work/data"
echo "SMOKE OK"
EOF
chmod +x ~/bashlab/opsctl/test/smoke.sh
~/bashlab/opsctl/test/smoke.sh; echo "rc=$?"
mockapi listening on http://127.0.0.1:18000 opsctl 0.3.0 … WARN opsctl[23088]: health fail: http://127.0.0.1:18000/flaky?fail=2&key=smoke-23074 code=503 curl_rc=0 … WARN opsctl[23088]: attempt 1/4 failed (exit 1), retrying in 0.554s … WARN opsctl[23088]: health fail: http://127.0.0.1:18000/flaky?fail=2&key=smoke-23074 code=503 curl_rc=0 … WARN opsctl[23088]: attempt 2/4 failed (exit 1), retrying in 1.286s … INFO opsctl[23088]: health ok: http://127.0.0.1:18000/flaky?fail=2&key=smoke-23074 code=200 time=0.001236s … INFO opsctl[23088]: attempt 3 succeeded: health::probe http://127.0.0.1:18000/flaky?fail=2&key=smoke-23074 5 200 … WARN opsctl[23103]: health fail: http://127.0.0.1:18000/status/500 code=500 curl_rc=0 … WARN opsctl[23103]: attempt 1/2 failed (exit 1), retrying in 0.123s … WARN opsctl[23103]: health fail: http://127.0.0.1:18000/status/500 code=500 curl_rc=0 … ERROR opsctl[23103]: giving up after 2 attempts (exit 1): health::probe http://127.0.0.1:18000/status/500 5 200 … INFO opsctl[23115]: backup created: /tmp/tmp.2EhZFQnGOY/bk/data-20261117T080147Z.tar.gz (4.0K) SMOKE OK rc=0
.github/workflows/opsctl.yml, following paragraph 1 of the “Commands” page, and simplify the Smoke step to run: opsctl/test/smoke.sh. (GitLab users: script: [opsctl/test/smoke.sh].)actionlint (GitHub) or GitLab's CI Lint page; after pushing, check the results and the summary on the Actions / Pipelines page.fail=2 to fail=9, push, confirm the job fails and the log contains health fail / giving up entry, and the artifact is still uploaded (if: always() / when: always). Revert and push again.Problem: A GitHub Actions step run: curl -s "$CONFIG_URL" | jq . > config.json (no shell specified → bash -e no pipefail). The config service returned a 500 HTML page and jq errored…, but this time curl returned an empty response,jq . with empty input, jq printed nothing and exited 0, so the step passed and the empty config was packaged and published. Fix:defaults.run.shell: bash; curl -fsS --fail-with-body; jq -e validate required fields; move the logic into a script with strict mode. Limitation: Platform defaults can change over time; a script that sets strict mode itself is the most reliable.
Problem: While debugging, we added set -x, and the script ran curl -H "Authorization: Bearer $(get_token)", but the token fetched at runtime was not in the secret list, so it appeared verbatim in the logs of the public repository. Fix: Mask runtime-generated sensitive values immediately ::add-mask::; do not pass tokens on the command line (-H @file); when debugging, use set -x but for sensitive sections, use { set +x; } 2>/dev/null; rotate the leaked token. Limitation: Masking only works for exactly matching strings.
Problem: Two merges in a row triggered two deploy jobs that ran interleaved on the same host (the Module 4 lock works on the host, so the second job failed outright, and developers kept retrying, mistakenly thinking it was a version problem). Fix: Serialize at the CI layer (concurrency: deploy-prod and cancel-in-progress: false; GitLab resource_group), keep the host-level flock as a second line of defense, and make lock-conflict messages clear (opsctl's util::lock deploy reports lock busy: …/var/lock/deploy.lock (another opsctl running?)). Limitation: Serialization queues jobs, so long deployments need a timeout set.
Cause:shell: bash With pipefail,cmd | head -1 in the pipeline, head exits early, so the upstream gets SIGPIPE (128+13).
Fix: Use grep -m1,awk 'NR==1{print; exit}' read all of the input, or sed -n '1p'; when truncation is really needed, explicitly tolerate it: { cmd || [[ $? -eq 141 ]]; } | head -1.
Cause: The file was committed from Windows, so it has no executable bit.
git ls-files -s opsctl/bin/opsctl # 100644 = no executable bit
Fix:git update-index --chmod=+x opsctl/bin/opsctl and commit; or in CI, invoke it with bash opsctl/bin/opsctl . Also check CRLF (.gitattributes: *.sh text eol=lf).
Cause: Alpine ships BusyBox tools by default, whose options differ from GNU's.
Fix:apk add --no-cache coreutils util-linux findutils; or switch to a Debian / Ubuntu image. Lesson 7 adds a multi-platform test matrix to CI.
Cause: The subject in the federated credential / trust policy (repo, branch, environment) does not match the actual token, or is missing permissions: id-token: write.
Fix: Check the subject format (for example, repo:org/repo:ref:refs/heads/main or …:environment:prod); see the OIDC section of the GitHub / GitLab courses.
health, and the step itself does not fail when the check fails.if opsctl health -r 3 "$URL"; then r=OK; else r=FAIL; fi echo "health=$r" >> "$GITHUB_OUTPUT"
opsctl backup, and keeps the backups/ directory for 7 days even on failure.nightly-backup:
script:
- opsctl/bin/opsctl backup -o backups -k 7 data
artifacts:
when: always
paths: [backups/]
expire_in: 7 days
rules:
- if: $CI_PIPELINE_SOURCE == "schedule"① How it is invoked in the YAML: ./deploy.sh | tee log and the shell has no pipefail (GitHub, no shell specified); ② whether it is swallowed by || true,continue-on-error: true,allow_failure: true ; ③ in GitLab, multi-line commands are folded into one command and only the last one is checked (for example, when the last one is echo done); ④ inside the script, a different branch runs in CI (CI=true when it is set, skips checks, and when a tool is missing command -v x || exit 0); ⑤ a failure happens in a background process and there is no wait to collect its exit code.
This lesson cannot directly generate a video/MP3, so a storyboard and narration script are provided instead.
shell: bash, with the expanded command shown below each.lib/cmd_health.sh,lib/cmd_backup.sh,lib/cmd_deploy.sh, with the functions being cmd::health,cmd::backup,cmd::deploy, dispatched automatically by the entry point.# opsctl-summary: comment (help and discovery depend on it); util::usage_error / util::die <msg> [code] / util::require_cmd (EX_* = 0/1/2/3); reuse util::retry,util::lock,util::cleanup_add; options go through config::set_flag / config::get (flag > OPSCTL_<KEY> > config file > default).~/bashlab/opsctl/ ├── bin/opsctl # change 1 line: readonly OPSCTL_VERSION="0.3.0" (the rest is the v0.2 from Lesson 4) ├── lib/log.sh # unchanged: log::debug/info/warn/error → stderr ├── lib/util.sh # unchanged: EX_*, util::die, util::usage_error, util::require_cmd, │ # util::cleanup_add, util::mktemp_dir, util::lock, util::retry ├── lib/config.sh # changed: OPSCTL_DEFAULTS gains 8 new keys (health_* / backup_* / deploy_*) ├── lib/cmd_health.sh # new: cmd::health — health::probe + util::retry (Module 1) ├── lib/cmd_backup.sh # new: cmd::backup — util::lock + same-directory mktemp + atomic mv + rotation (Module 5) ├── lib/cmd_deploy.sh # new: cmd::deploy — deploy::switch / deploy::previous + health check + rollback (Module 4) ├── lib/cmd_servers.sh cmd_config.sh cmd_export.sh cmd_doctor.sh # Lessons 3 and 4, unchanged ├── etc/opsctl.conf # key = value; parsed only by config::load_file against an allowlist, never sourced ├── var/lock/ # util::lock lock files (backup.lock, deploy.lock) └── test/mockapi.py test/smoke.sh # Module 7 smoke tests
time level opsctl[PID]: message), one set of exit codes (EX_OK/EX_ERR/EX_USAGE/EX_DEP = 0/1/2/3), one configuration precedence — cron, systemd and CI only need to understand one set of rules.util::retry, locks use util::lock, temp files are registered with util::cleanup_add ; the EXIT trap cleans them up, so subcommands no longer each write their own trap / flock.opsctl::list_commands reads each file's # opsctl-summary: comment to generate opsctl --help,opsctl::load_command loads them by name lib/cmd_<name>.sh.# shellcheck shell=bash, line 2 is # opsctl-summary: … (without it, opsctl --help the command shows no description in help; the file name must be cmd_<name>.sh, and define cmd::<name>).<name>::usage, and handle -h|--help——opsctl help health is the function that actually executes cmd::health --help.while (($#)); case to parse short and long options; missing argument / unknown option → util::usage_error (exit code 2, and print the hint Try 'opsctl --help').config::set_flag <key> <value>, then read them uniformly with config::get <key> <var> : precedence is flag > environment variable OPSCTL_<KEY> > etc/opsctl.conf > OPSCTL_DEFAULTS. New keys must be added to OPSCTL_DEFAULTS, otherwise same-named keys in the config file are ignored as “unknown key”.util::require_cmd (when missing, missing required command(s): …, exit code 3); mutually exclusive util::lock <name>; temp paths util::cleanup_add.return 1 (let the caller decide, for example, deploy calls health and then rolls back); only usage, dependency and unrecoverable errors use util::die.| Subcommand / function | Options | Config keys (environment variables) and defaults | Exit codes |
|---|---|---|---|
health URLcmd::health,health::probe,health::usage | -t/--timeout,-r/--retries,-e/--expect | health_timeout=5 (OPSCTL_HEALTH_TIMEOUT),health_retries=4,health_expect=200 | 0 healthy · 1 retries exhausted · 2 usage · 3 curl missing |
backup SRC_DIRcmd::backup,backup::usage | -o/--out-dir,-k/--keep | backup_dir=~/bashlab/backups (OPSCTL_BACKUP_DIR),backup_keep=7 | 0 · 1 lock busy / failed · 2 usage · 3 tar/sha256sum/flock missing |
deploycmd::deploy,deploy::switch,deploy::previous,deploy::usage | -a/--artifact,-d/--root,-u/--url,-k/--keep,--rollback | deploy_root=~/bashlab/deploy (OPSCTL_DEPLOY_ROOT),deploy_keep=5,deploy_health_url=empty (no check) | 0 · 1 health check failed and rolled back / lock busy / no version to roll back to · 2 usage |
opsctl currently has a few dozen lines per subcommand, and the logic is mostly “call external commands + check exit codes”, so Bash fits very well. Consider rewriting a subcommand in Python / Go when these signals appear: you need to parse complex JSON and do heavy computation; you need a concurrent HTTP client with fine-grained connection pooling; or a single file exceeds 200–300 lines and is hard to test. Lesson 7 adds a safety net to the existing code using bats + ShellCheck.
exit 1 directly in a subcommand is the simplest”—cmd::health is called by cmd::deploy , and if it internally calls exit deploy then has no time to roll back; for business failures, use return 1. ② “In deploy, calling cmd::health is enough”—the dispatcher only loads lib/cmd_deploy.sh, so you must first opsctl::load_command health (tested: not loading it reports cmd::health: command not found, and it is treated as a failed health check, triggering a rollback). ③ “Writing your own trap … EXIT temp-file cleanup”—this overrides the EXIT trap of the v0.2 entry point (util::_on_exit); use util::cleanup_add to register it. ④ “The lock file must be removed on exit”—flock The lock is released automatically when the file descriptor closes, and the lock file is kept long-term (per the Lesson 4 convention, located at var/lock/).Pick a command and step through it to see how the entry point loads the library and config, how it dispatches, how the subcommand parses arguments, which external commands it calls, where the log goes, and what the final exit code is. The logs are real output from this lesson (timestamps are from a sample environment).
The steps below were actually run on the real v0.2.0 code produced by the combined Lesson 3 and 4 lab (code rebuilt by extracting it from the two lesson pages; Bash 5.2.21 / WSL2). All output is real.
cd ~/bashlab/opsctl grep -n '^readonly OPSCTL_VERSION=' bin/opsctl sed -i 's/^readonly OPSCTL_VERSION="0\.2\.0"$/readonly OPSCTL_VERSION="0.3.0"/' bin/opsctl grep -n '^readonly OPSCTL_VERSION=' bin/opsctl
30:readonly OPSCTL_VERSION="0.2.0" 30:readonly OPSCTL_VERSION="0.3.0"
The sed pattern matches the Lesson 4 version word for word (readonly plus double quotes). If the second grep still shows 0.2.0, your bin/opsctl differs from Lesson 4, so edit it by hand.
keys=$(mktemp) cat > "$keys" <<'EOF' [health_timeout]=5 [health_retries]=4 [health_expect]=200 [backup_dir]="$HOME/bashlab/backups" [backup_keep]=7 [deploy_root]="$HOME/bashlab/deploy" [deploy_keep]=5 [deploy_health_url]="" EOF sed -i "/^ \[output\]=table\$/r $keys" lib/config.sh; rm -f "$keys" sed -n '/^declare -gA OPSCTL_DEFAULTS=(/,/^)/p' lib/config.sh
declare -gA OPSCTL_DEFAULTS=( [env]=dev [data_dir]="$HOME/bashlab/data" [log_level]=info [output]=table [health_timeout]=5 [health_retries]=4 [health_expect]=200 [backup_dir]="$HOME/bashlab/backups" [backup_keep]=7 [deploy_root]="$HOME/bashlab/deploy" [deploy_keep]=5 [deploy_health_url]="" )
Why change config.sh instead of adding the defaults in the cmd file? Because config::init keys are parsed before dispatch etc/opsctl.conf, at which point the cmd files are not loaded yet, so keys not on the allowlist get a warning and are ignored. In opsctl.conf you can write backup_keep = 14, or use OPSCTL_BACKUP_KEEP=14 to override.
# shellcheck shell=bash
# opsctl-summary: HTTP health check with retries and backoff (health [-t SEC] [-r N] [-e CODE] URL)
# lib/cmd_health.sh — v0.3 (Lesson 6): curl probe + util::retry (exponential backoff + full jitter)
# Exit codes: 0 healthy · 1 still unhealthy after retries are exhausted · 2 usage error · 3 curl missing
health::usage() {
cat <<EOF
Usage: ${OPSCTL_PROG:-opsctl} health [options] URL
Probe URL until it returns the expected HTTP status, retrying with
exponential backoff and full jitter (util::retry).
Options:
-t, --timeout SEC connect timeout; total per attempt is 2x (config: health_timeout)
-r, --retries N attempts in total (config: health_retries)
-e, --expect CODE expected HTTP status (config: health_expect)
-h, --help show this help
EOF
}
health::probe() { # health::probe <url> <timeout> <expect>: one probe; returns 0 on success, otherwise 1
local url=$1 timeout=$2 expect=$3 out code t rc=0
out=$(curl -sS -o /dev/null -w '%{http_code} %{time_total}' \
--connect-timeout "$timeout" --max-time "$((timeout * 2))" -- "$url") || rc=$?
read -r code t <<<"${out:-000 0}"
if ((rc == 0)) && [[ $code == "$expect" ]]; then
log::info "health ok: $url code=$code time=${t}s"
return 0
fi
log::warn "health fail: $url code=$code curl_rc=$rc"
return 1
}
cmd::health() {
local url="" timeout tries expect
while (($#)); do
case $1 in
-t | --timeout | -r | --retries | -e | --expect)
[[ $# -ge 2 && -n $2 ]] || util::usage_error "option '$1' requires an argument"
case $1 in
-t | --timeout) config::set_flag health_timeout "$2" ;;
-r | --retries) config::set_flag health_retries "$2" ;;
*) config::set_flag health_expect "$2" ;;
esac
shift 2 ;;
-h | --help) health::usage; return 0 ;;
--) shift; break ;;
-*) util::usage_error "unknown option for 'health': $1" ;;
*) [[ -z $url ]] || util::usage_error "unexpected argument: $1"; url=$1; shift ;;
esac
done
if (($#)); then # arguments after "--" (used when the URL starts with -)
[[ -z $url && $# -eq 1 ]] || util::usage_error "unexpected argument(s): $*"
url=$1
fi
[[ -n $url ]] || util::usage_error "missing URL"
[[ $url =~ ^https?:// ]] || util::usage_error "URL must start with http:// or https://: $url"
config::get health_timeout timeout || return 1
config::get health_retries tries || return 1
config::get health_expect expect || return 1
[[ $timeout =~ ^[1-9][0-9]*$ && $tries =~ ^[1-9][0-9]*$ && $expect =~ ^[1-5][0-9][0-9]$ ]] \
|| util::usage_error "invalid timeout/retries/expect: $timeout/$tries/$expect"
util::require_cmd curl
# util::retry handles backoff and the "giving up" log; on failure it returns 1 (business failure; the caller decides whether to roll back)
util::retry "$tries" 1 health::probe "$url" "$timeout" "$expect" || return 1
}
Design: health::probe It only does “one probe + log”: returns 0 on success, 1 on failure. Retries, exponential backoff, full jitter, and the “giving up” log are all delegated to util::retry <tries> <delay> <cmd…> from Lesson 4. util::retry Exit codes 2, 126 and 127 are treated as non-retryable, and since probe returns only 0 or 1, it won't misjudge. out=$(curl …) || rc=$? It runs in a conditional context, so it won't trigger the ERR trap's call-stack report.
# shellcheck shell=bash
# opsctl-summary: archive a directory with checksum and rotation (backup [-o DIR] [-k N] SRC_DIR)
# lib/cmd_backup.sh — v0.3 (Lesson 6): util::lock → mktemp in the same directory → tar → verify → atomic mv → sha256 → rotate
backup::usage() {
cat <<EOF
Usage: ${OPSCTL_PROG:-opsctl} backup [options] SRC_DIR
Create <out_dir>/<name>-YYYYmmddTHHMMSSZ.tar.gz (+ .sha256) atomically,
then keep only the newest N archives of that name.
Options:
-o, --out-dir DIR where archives go (config: backup_dir)
-k, --keep N archives to keep, N >= 1 (config: backup_keep)
-h, --help show this help
EOF
}
cmd::backup() {
local src="" outdir keep
while (($#)); do
case $1 in
-o | --out-dir | -k | --keep)
[[ $# -ge 2 && -n $2 ]] || util::usage_error "option '$1' requires an argument"
if [[ $1 == -o || $1 == --out-dir ]]; then config::set_flag backup_dir "$2"; else config::set_flag backup_keep "$2"; fi
shift 2 ;;
-h | --help) backup::usage; return 0 ;;
-*) util::usage_error "unknown option for 'backup': $1" ;;
*) [[ -z $src ]] || util::usage_error "unexpected argument: $1"; src=$1; shift ;;
esac
done
[[ -n $src ]] || util::usage_error "missing SRC_DIR"
[[ -d $src ]] || util::usage_error "not a directory: $src"
config::get backup_dir outdir || return 1
config::get backup_keep keep || return 1
[[ $keep =~ ^[1-9][0-9]*$ ]] || util::usage_error "keep must be a positive integer: $keep"
util::require_cmd tar sha256sum
src=$(cd -- "$src" && pwd)
mkdir -p -- "$outdir"
util::lock backup # only one backup may run at a time (the v0.2 lock)
local name ts final tmp base old
name=${src##*/}
ts=$(date -u +%Y%m%dT%H%M%SZ)
final=$outdir/$name-$ts.tar.gz
base=${final##*/}
tmp=$(mktemp "$outdir/.$name.XXXXXX.part") # same directory → mv is an atomic rename(2)
util::cleanup_add "$tmp" # removed by the EXIT trap on failure or signal; no longer exists after mv
tar -C "$(dirname -- "$src")" -czf "$tmp" -- "$name"
tar -tzf "$tmp" >/dev/null # give it its final name only once the archive is readable
mv -f -- "$tmp" "$final"
(cd -- "$outdir" && sha256sum -- "$base" >"$base.sha256")
log::info "backup created: $final ($(du -h -- "$final" | cut -f1))"
# rotation: the names contain UTC timestamps → reverse order runs newest to oldest; skip the newest keep ones
while IFS= read -r -d '' old; do
rm -f -- "$old" "$old.sha256"
log::info "rotated: $old"
done < <(find "$outdir" -maxdepth 1 -type f -name "$name-*.tar.gz" -print0 | sort -z -r | tail -z -n +"$((keep + 1))")
}
Compared with the standalone script in Module 5: the lock now uses util::lock backup (var/lock/backup.lock, and when busy it util::die exits with 1); temp files are handed to util::cleanup_add, no longer trap … EXIT; temp files still use mktemp "$outdir/…" placed in the target directory, not in util::mktemp_dir 's /tmp— only mv within the same filesystem is an atomic rename(2).
# shellcheck shell=bash
# opsctl-summary: atomic release switch with health check and rollback (deploy -a PKG [-u URL] | --rollback)
# lib/cmd_deploy.sh — v0.3 (Lesson 6): <root>/releases/<UTC timestamp>/ + <root>/current -> releases/<timestamp>
deploy::usage() {
cat <<EOF
Usage: ${OPSCTL_PROG:-opsctl} deploy -a PKG.tar.gz [options]
${OPSCTL_PROG:-opsctl} deploy --rollback [-d DIR]
Unpack PKG into <root>/releases/<timestamp>, switch <root>/current atomically,
run the health check, roll back automatically if it fails, prune old releases.
Options:
-a, --artifact PKG release tarball (must contain version.txt)
-d, --root DIR deploy root (config: deploy_root)
-u, --url URL health check URL (config: deploy_health_url; empty = skip)
-k, --keep N releases to keep, N >= 1 (config: deploy_keep)
--rollback switch current back to the previous release
-h, --help show this help
EOF
}
deploy::switch() { # deploy::switch <root> <target>: temp link + rename(2), atomically replaces current
ln -sfn -- "$2" "$1/.current.tmp"
mv -Tf -- "$1/.current.tmp" "$1/current" # GNU mv -T: treats current as a file, not as the target directory
}
deploy::previous() { # deploy::previous <root>: prints the release before current (sorted by name); returns 1 if none
local root=$1 cur rel prev=""
cur=$(readlink -- "$root/current") || return 1
while IFS= read -r rel; do
if [[ releases/$rel == "$cur" ]]; then
[[ -n $prev ]] || return 1
printf 'releases/%s\n' "$prev"
return 0
fi
prev=$rel
done < <(find "$root/releases" -mindepth 1 -maxdepth 1 -type d -printf '%f\n' | sort)
return 1
}
cmd::deploy() {
local artifact="" rollback=0 root url keep
while (($#)); do
case $1 in
-a | --artifact | -d | --root | -u | --url | -k | --keep)
[[ $# -ge 2 && -n $2 ]] || util::usage_error "option '$1' requires an argument"
case $1 in
-a | --artifact) artifact=$2 ;;
-d | --root) config::set_flag deploy_root "$2" ;;
-u | --url) config::set_flag deploy_health_url "$2" ;;
*) config::set_flag deploy_keep "$2" ;;
esac
shift 2 ;;
--rollback) rollback=1; shift ;;
-h | --help) deploy::usage; return 0 ;;
*) util::usage_error "unknown argument for 'deploy': $1" ;;
esac
done
config::get deploy_root root || return 1
config::get deploy_health_url url || return 1
config::get deploy_keep keep || return 1
[[ $keep =~ ^[1-9][0-9]*$ ]] || util::usage_error "keep must be a positive integer: $keep"
mkdir -p -- "$root/releases"
util::lock deploy # two deploys running at once = disaster
if ((rollback)); then
local prev
prev=$(deploy::previous "$root") || util::die "no previous release to roll back to"
deploy::switch "$root" "$prev"
log::warn "rolled back: current -> $prev"
return 0
fi
[[ -n $artifact ]] || util::usage_error "missing -a PKG.tar.gz"
[[ -f $artifact ]] || util::usage_error "artifact not found: $artifact"
util::require_cmd tar
if [[ -n $url ]]; then # the dispatcher only loads cmd_deploy.sh; load health by name before reusing it
opsctl::load_command health || util::die "cannot load lib/cmd_health.sh"
fi
local ts rel old cur r
ts=$(date -u +%Y%m%dT%H%M%SZ)
rel=$root/releases/$ts
[[ ! -e $rel ]] || util::die "$rel already exists (two deploys within one second?)"
mkdir -p -- "$rel"
tar -xzf "$artifact" -C "$rel"
if [[ ! -f $rel/version.txt ]]; then
rm -rf -- "${rel:?}"
util::die "artifact has no version.txt, aborted (current unchanged)"
fi
old=$(readlink -- "$root/current" || true)
deploy::switch "$root" "releases/$ts"
log::info "switched: current -> releases/$ts (previous: ${old:-none}) version $(<"$rel/version.txt")"
if [[ -n $url ]] && ! cmd::health -r 3 -t 2 "$url"; then
if [[ -n $old ]]; then
deploy::switch "$root" "$old"
log::error "health check failed, rolled back: current -> $old"
else
log::error "health check failed and there is no previous release"
fi
return 1
fi
# cleanup: keep the newest keep releases, never delete the one current points to
cur=$(readlink -- "$root/current")
while IFS= read -r r; do
[[ releases/$r == "$cur" ]] && continue
rm -rf -- "${root:?}/releases/${r:?}"
log::info "pruned: releases/$r"
done < <(find "$root/releases" -mindepth 1 -maxdepth 1 -type d -printf '%f\n' | sort -r | tail -n +"$((keep + 1))")
log::info "deploy ok: releases/$ts"
}
Key points: ① opsctl::load_command health (functions in bin/opsctl) load health when needed; ② ! cmd::health -r 3 -t 2 "$url" runs in a conditional context, so a failure inside health does not trigger errexit / ERR reporting; ③ release directory names are generated by the script, so a plain find -printf '%f\n' ls listing is enough; ④ "${rel:?}" prevents an empty variable from causing rm -rf an accidental deletion.
opsctl config show the new keyssed -i 's/^ for key in env data_dir log_level output; do$/ for key in env data_dir log_level output health_timeout health_retries health_expect backup_dir backup_keep deploy_root deploy_keep deploy_health_url; do/' lib/cmd_config.sh OPSCTL_BACKUP_KEEP=14 bin/opsctl config
KEY VALUE SOURCE env dev file ~/bashlab/opsctl/etc/opsctl.conf data_dir ~/bashlab/data file ~/bashlab/opsctl/etc/opsctl.conf log_level info file ~/bashlab/opsctl/etc/opsctl.conf output table file ~/bashlab/opsctl/etc/opsctl.conf health_timeout 5 default health_retries 4 default health_expect 200 default backup_dir ~/bashlab/backups default backup_keep 14 env OPSCTL_BACKUP_KEEP deploy_root ~/bashlab/deploy default deploy_keep 5 default deploy_health_url default
Lesson 3's cmd::config uses a fixed key list; this step just completes the list (the column width was designed for 4 short keys, so long keys will be misaligned, but that does not affect functionality).
export NO_COLOR=1 bin/opsctl -V bin/opsctl --help | sed -n '/^Commands:/,/^ help/p' bin/opsctl help health; echo "rc=$?"
opsctl 0.3.0 Commands: backup archive a directory with checksum and rotation (backup [-o DIR] [-k N] SRC_DIR) config show effective configuration and where each value came from deploy atomic release switch with health check and rollback (deploy -a PKG [-u URL] | --rollback) doctor check bash version, dependencies, data and lock dirs (read-only) export export servers.csv atomically (export servers --out FILE [--env ENV]) health HTTP health check with retries and backoff (health [-t SEC] [-r N] [-e CODE] URL) servers query the server inventory (servers list --env ENV) help [COMMAND] show help for a command Usage: opsctl health [options] URL Probe URL until it returns the expected HTTP status, retrying with exponential backoff and full jitter (util::retry). Options: -t, --timeout SEC connect timeout; total per attempt is 2x (config: health_timeout) -r, --retries N attempts in total (config: health_retries) -e, --expect CODE expected HTTP status (config: health_expect) -h, --help show this help rc=0
B=http://127.0.0.1:8000 bin/opsctl health; echo "rc=$?" bin/opsctl health "$B/flaky?fail=2&key=h"; echo "rc=$?" bin/opsctl health -r 2 "$B/status/500"; echo "rc=$?"
2026-11-17T03:01:27-0500 ERROR opsctl[22796]: missing URL Try 'opsctl --help' for more information. rc=2 2026-11-17T03:01:28-0500 WARN opsctl[22811]: health fail: http://127.0.0.1:8000/flaky?fail=2&key=h code=503 curl_rc=0 2026-11-17T03:01:28-0500 WARN opsctl[22811]: attempt 1/4 failed (exit 1), retrying in 0.677s 2026-11-17T03:01:28-0500 WARN opsctl[22811]: health fail: http://127.0.0.1:8000/flaky?fail=2&key=h code=503 curl_rc=0 2026-11-17T03:01:28-0500 WARN opsctl[22811]: attempt 2/4 failed (exit 1), retrying in 1.037s 2026-11-17T03:01:29-0500 INFO opsctl[22811]: health ok: http://127.0.0.1:8000/flaky?fail=2&key=h code=200 time=0.002314s 2026-11-17T03:01:29-0500 INFO opsctl[22811]: attempt 3 succeeded: health::probe http://127.0.0.1:8000/flaky?fail=2&key=h 5 200 rc=0 2026-11-17T03:01:29-0500 WARN opsctl[22826]: health fail: http://127.0.0.1:8000/status/500 code=500 curl_rc=0 2026-11-17T03:01:29-0500 WARN opsctl[22826]: attempt 1/2 failed (exit 1), retrying in 0.381s 2026-11-17T03:01:30-0500 WARN opsctl[22826]: health fail: http://127.0.0.1:8000/status/500 code=500 curl_rc=0 2026-11-17T03:01:30-0500 ERROR opsctl[22826]: giving up after 2 attempts (exit 1): health::probe http://127.0.0.1:8000/status/500 5 200 rc=1
“Full jitter”: after the nth failure, wait random(0, min(30, 1×2^(n-1))) seconds, so the second wait can also be shorter than the first. The cap is controlled by RETRY_MAX_DELAY (default 30).
for i in 1 2 3; do bin/opsctl backup -k 2 ~/bashlab/data; sleep 1.1; done ( flock var/lock/backup.lock sleep 3 ) & sleep 0.5 bin/opsctl backup ~/bashlab/data; echo "lock rc=$?"; wait bin/opsctl backup /nonexistent; echo "rc=$?"
2026-11-17T03:01:35-0500 INFO opsctl[22857]: backup created: ~/bashlab/backups/data-20261117T080135Z.tar.gz (4.0K) 2026-11-17T03:01:36-0500 INFO opsctl[22887]: backup created: ~/bashlab/backups/data-20261117T080136Z.tar.gz (4.0K) 2026-11-17T03:01:37-0500 INFO opsctl[22917]: backup created: ~/bashlab/backups/data-20261117T080137Z.tar.gz (4.0K) 2026-11-17T03:01:37-0500 INFO opsctl[22917]: rotated: ~/bashlab/backups/data-20261117T080135Z.tar.gz 2026-11-17T03:01:38-0500 ERROR opsctl[22955]: lock busy: ~/bashlab/opsctl/var/lock/backup.lock (another opsctl running?) lock rc=1 2026-11-17T03:01:41-0500 ERROR opsctl[22963]: not a directory: /nonexistent Try 'opsctl --help' for more information. rc=2
for v in 1.0.0 1.1.0 1.2.0; do bin/opsctl deploy -a ~/bashlab/m4/app-$v.tar.gz -u http://127.0.0.1:8080/healthz -k 3 echo "deploy $v rc=$? serving=$(curl -s http://127.0.0.1:8080/version.txt)"; sleep 1.1 done bin/opsctl deploy --rollback; echo "rb rc=$?"; curl -s http://127.0.0.1:8080/version.txt
2026-11-17T03:02:29-0500 INFO opsctl[23414]: switched: current -> releases/20261117T080229Z (previous: none) version 1.0.0 2026-11-17T03:02:29-0500 INFO opsctl[23414]: health ok: http://127.0.0.1:8080/healthz code=200 time=0.003412s 2026-11-17T03:02:29-0500 INFO opsctl[23414]: deploy ok: releases/20261117T080229Z deploy 1.0.0 rc=0 serving=1.0.0 2026-11-17T03:02:30-0500 INFO opsctl[23442]: switched: current -> releases/20261117T080230Z (previous: releases/20261117T080229Z) version 1.1.0 2026-11-17T03:02:30-0500 INFO opsctl[23442]: health ok: http://127.0.0.1:8080/healthz code=200 time=0.000824s 2026-11-17T03:02:30-0500 INFO opsctl[23442]: deploy ok: releases/20261117T080230Z deploy 1.1.0 rc=0 serving=1.1.0 2026-11-17T03:02:31-0500 INFO opsctl[23470]: switched: current -> releases/20261117T080231Z (previous: releases/20261117T080230Z) version 1.2.0 2026-11-17T03:02:31-0500 WARN opsctl[23470]: health fail: http://127.0.0.1:8080/healthz code=404 curl_rc=0 2026-11-17T03:02:31-0500 WARN opsctl[23470]: attempt 1/3 failed (exit 1), retrying in 0.665s 2026-11-17T03:02:32-0500 WARN opsctl[23470]: health fail: http://127.0.0.1:8080/healthz code=404 curl_rc=0 2026-11-17T03:02:32-0500 WARN opsctl[23470]: attempt 2/3 failed (exit 1), retrying in 1.817s 2026-11-17T03:02:34-0500 WARN opsctl[23470]: health fail: http://127.0.0.1:8080/healthz code=404 curl_rc=0 2026-11-17T03:02:34-0500 ERROR opsctl[23470]: giving up after 3 attempts (exit 1): health::probe http://127.0.0.1:8080/healthz 2 200 2026-11-17T03:02:34-0500 ERROR opsctl[23470]: health check failed, rolled back: current -> releases/20261117T080230Z deploy 1.2.0 rc=1 serving=1.1.0 2026-11-17T03:02:35-0500 WARN opsctl[23506]: rolled back: current -> releases/20261117T080229Z rb rc=0 1.0.0
The bad-version directory releases/20261117T080231Z is kept for troubleshooting; on the next successful deploy, it is cleaned up per -k .
~/bashlab/opsctl You should be in the v0.2.0 from Lesson 4 (Module 0, step 3); mockapi is running on 8000; the three Module 4 packages are in ~/bashlab/m4/.
cd ~/bashlab/opsctl && git status --short && git describe --tags export NO_COLOR=1 PATH="$HOME/bashlab/opsctl/bin:$PATH"
OPSCTL_DEFAULTS, add lib/cmd_health.sh,lib/cmd_backup.sh,lib/cmd_deploy.sh (line 2 of each file is # opsctl-summary:). Then check:
for f in bin/opsctl lib/*.sh; do bash -n "$f" || echo "SYNTAX FAIL: $f"; done grep -H '^# opsctl-summary:' lib/cmd_*.sh | wc -l # 7: servers config export doctor + 3 new commands command -v shellcheck >/dev/null && shellcheck -x bin/opsctl lib/*.sh opsctl -V && opsctl help deploy | head -3
opsctl health http://127.0.0.1:8000/healthz; echo "rc=$?" # 0 opsctl health -r 4 "http://127.0.0.1:8000/flaky?fail=2&key=lab8"; echo "rc=$?" # 0 (succeeds on 3rd try) opsctl health -r 2 -t 1 "http://127.0.0.1:8000/slow?sec=5"; echo "rc=$?" # 1 (2-second timeout each time) OPSCTL_HEALTH_RETRIES=1 opsctl health http://127.0.0.1:8000/status/503; echo "rc=$?" # 1, only tries once (env var takes effect) opsctl health -x http://127.0.0.1:8000/healthz; echo "rc=$?" # 2 (unknown option)
Want to see exit code 3? Temporarily hiding curl without affecting bash itself is hard — Lesson 7 uses bats to build a PATH that is missing only curl, for testing util::require_cmd.
for i in 1 2 3; do opsctl backup -k 2 ~/bashlab/data; sleep 1.1; done ls -1 ~/bashlab/backups | grep -c 'tar.gz$' # 2 (cd ~/bashlab/backups && sha256sum -c ./*.sha256) ls -A ~/bashlab/backups | grep -c part # 0: no leftover temp files
mkdir -p ~/bashlab/deploy python3 -m http.server 8080 --bind 127.0.0.1 -d ~/bashlab/deploy/current >/dev/null 2>&1 & echo $! > /tmp/http8080.pid for v in 1.0.0 1.1.0 1.2.0; do opsctl deploy -a ~/bashlab/m4/app-$v.tar.gz -u http://127.0.0.1:8080/healthz -k 3 echo "deploy $v rc=$? serving=$(curl -s http://127.0.0.1:8080/version.txt)"; sleep 1.1 done opsctl deploy --rollback; curl -s http://127.0.0.1:8080/version.txt
deploy 1.0.0 rc=0 serving=1.0.0 deploy 1.1.0 rc=0 serving=1.1.0 deploy 1.2.0 rc=1 serving=1.1.0 1.0.0
test/smoke.sh, expecting the last line to be SMOKE OK (verified in a real run).kill "$(cat /tmp/http8080.pid)"; rm -f /tmp/http8080.pid rm -rf ~/bashlab/deploy # keep backups and opsctl cd ~/bashlab/opsctl && git add -A && git commit -m "opsctl v0.3: health, backup, deploy" && git tag v0.3.0 kill "$(cat ~/bashlab/mock/mock.pid)" # stop mockapi when the course ends
Problem: The team has check_web.sh,bk.sh, and release.sh scripts from different authors: one returns 0 on failure, one writes its logs to stdout and floods cron email, and one exit which kills the caller. Approach: Unified as opsctl subcommands: logs go to stderr, business failure return 1, usage error 2, dependency 3; systemd timers and CI only call opsctl …. Limitations: During migration, keep the old scripts as thin wrappers around opsctl to avoid a big-bang cutover.
Problem: Another team's tool runs its config file directly with source, and someone wrote DEPLOY_ROOT=$(curl …), so every run hits the network, and even help fails. Approach: Since Lesson 3, opsctl has used config::load_file a parser that matches key = value keys against a whitelist and never sources the file — so v0.3's new keys must be registered in OPSCTL_DEFAULTS (otherwise they are warned about and ignored), which is why step 2 on the “Commands” tab exists. Limitations: Parse-only config files do not support variables or command substitution; for dynamic values, use environment variables OPSCTL_<KEY> or pass them as command-line options.
Problem: deploy calls health; on failure, health logs one ERROR and deploy logs another, so the alerting system doubles its ERROR count. Approach: Convention: “the outermost caller decides on ERROR”: called functions log each attempt at WARN and report results via return values; or add a quiet parameter. Limitations: The log-level convention must be written into the README; the Lesson 7 tests can assert on log content.
Start from the symptom, make choices step by step, and get the diagnosis and fix commands.
Cause:opsctl::load_command Requirements: the file name lib/cmd_health.sh, readable, sourceable (no syntax errors), and defines cmd::health. If any one of these is not met, you get unknown command (exit code 2).
bash -n lib/cmd_health.sh; grep -n '^cmd::' lib/cmd_health.sh; ls -l lib/cmd_health.sh
Cause: Missing # opsctl-summary: … comment line (note the space after the colon,opsctl::list_commands matched by the prefix '# opsctl-summary: ' ).
grep -H '^# opsctl-summary: ' lib/cmd_*.sh
Cause: The dispatcher only loads the cmd file that was called. Before deploy reuses health, it must load opsctl::load_command health (a pitfall we hit while writing this lesson: when not loaded, ! cmd::health returns 127, which is treated as “unhealthy”, so every deploy gets rolled back).
Cause: The new key was not added to lib/config.sh the OPSCTL_DEFAULTS,config::load_file so the allowlist ignored it.
Fix: Insert the key per step 2 on the “Commands” tab; use opsctl config (optional step 6) to confirm the source column shows file ….
Cause: Another opsctl backup (for example, the timer-triggered run) is still running; or you sourced the library in an interactive shell and called util::lock, so the fd is still open.
fuser -v ~/bashlab/opsctl/var/lock/backup.lock; pgrep -af 'opsctl backup'
Fix: Wait, or investigate the stuck process; run bin/opsctl as a separate process, which releases the lock on exit. When you need to queue, call util::lock backup 60 (waits 60 seconds).
health environment variable override to opsctl: without changing code, make one call expect status 204 and retry at most 6 times.OPSCTL_HEALTH_EXPECT=204 OPSCTL_HEALTH_RETRIES=6 opsctl health https://api.example.com/ping # or put it in etc/opsctl.conf: health_expect = 204 (priority: flag > env > file > default) # or: opsctl health -e 204 -r 6 https://api.example.com/ping
/srv/pkgs/app-latest.tar.gz to /srv/app and use http://127.0.0.1:8080/healthz to check.ExecStart=/opt/opsctl/bin/opsctl deploy -a /srv/pkgs/app-latest.tar.gz -d /srv/app -u http://127.0.0.1:8080/healthz
opsctl report: call 3 APIs (each one paginated), aggregate the results, and output Markdown. How would you design the files, functions, and exit codes?Files lib/cmd_report.sh, functions cmd::report; put the generic paginated GET into lib/api.sh (api::get_all URL, Module 1); dependencies util::require_cmd curl jq the three APIs can run in parallel as background jobs (results written to a temp directory,wait collect exit codes); if any API fails, output a partial report plus WARN and exit with code 1 (so CI goes red); usage error 2; all curl calls have timeouts and bounded retries; Markdown goes to stdout and logs go to stderr, which makes it easy to opsctl report > report.md; in Lesson 7, write bats tests for api::get_all (using mockapi).
opsctl is a project built for this course, so there is no matching public video. The videos below relate to parts of this module (all verified via YouTube oEmbed):
package::function scheme)This lesson cannot directly generate a video or MP3, so a storyboard and narration script are provided.
curl -fsS --connect-timeout 3 --max-time 10 \
--retry 4 --retry-max-time 60 --retry-connrefused "$url"
curl -sS --fail-with-body "$url" # 22 + keep error body (7.76+)
code=$(curl -sS -o body -w '%{http_code}' "$url") || code=000
curl -sS -o /dev/null -w '%header{link}\n' "$url" # 7.84+
jq -n --arg n web '{name:$n}' | curl -sS --json @- "$api" # 7.82+while [[ -n $url ]]; do
body=$(curl -fsS -D "$hdr" "$url")
jq -c '.[]' <<<"$body"
url=$(tr -d '\r' <"$hdr" |
sed -n 's/^[Ll]ink:.*<\([^>]*\)>; *rel="next".*/\1/p')
doneexport AWS_PAGER="" AZURE_CORE_OUTPUT=json sub=$(az account show --query id -o tsv) az vm list -d --query "[?powerState=='VM running'].[name,resourceGroup]" -o tsv aws sts get-caller-identity --query Account --output text aws ec2 describe-instances --filters Name=instance-state-name,Values=running \ --query 'Reservations[].Instances[].[InstanceId,PrivateIpAddress]' --output text # aws rc: 252 syntax · 253 credentials/config · 254 server error · 255 other
while IFS=$'\t' read -r id name ip; do …; done \ < <(jq -r '.[] | [.id, (.name // "-"), .ip] | @tsv' f.json) mapfile -t ids < <(jq -r '.[].id' f.json) jq -e '.items | length > 0' f.json >/dev/null || echo "empty" jq -r --arg env prod '.[] | select(.env==$env) | .name' f.json
ssh -n -o BatchMode=yes -o ConnectTimeout=5 \
-o StrictHostKeyChecking=accept-new "$h" cmd
xargs -0 -P 4 -n 2 bash -c 'f "$1" "$2"' _ # export -f f
parallel -j 8 --tag --timeout 60 --joblog jobs.tsv \
ssh -n -o BatchMode=yes {} uptime :::: hosts.txt
# xargs: any failure → 123; parallel → number of failed jobsts=$(date -u +%Y%m%dT%H%M%SZ)
mkdir -p releases/$ts && tar -xzf app.tgz -C releases/$ts
prev=$(readlink current || true)
ln -sfn releases/$ts .current.tmp && mv -Tf .current.tmp current
opsctl health -r 3 "$url" || { ln -sfn "$prev" .current.tmp; mv -Tf .current.tmp current; exit 1; }exec 9>"$dest/.lock"; flock -n 9 || exit 1
tmp=$(mktemp "$dest/.x.XXXXXX.part"); trap 'rm -f -- "$tmp"' EXIT
tar -C "$(dirname "$src")" -czf "$tmp" -- "$(basename "$src")"
tar -tzf "$tmp" >/dev/null && mv -f -- "$tmp" "$final"
(cd "$dest" && sha256sum -- "${final##*/}" > "${final##*/}.sha256")
find "$dest" -maxdepth 1 -name 'x-*.tar.gz' -print0 | sort -z -r | tail -z -n +8 |
while IFS= read -r -d '' f; do rm -f -- "$f" "$f.sha256"; done# crontab: PATH=… ; write % as \% 0 2 * * * flock -n /tmp/b.lock opsctl backup "$HOME/data" >>"$HOME/b.log" 2>&1 # .timer [Timer] OnCalendar=*-*-* 02:00:00 Persistent=true RandomizedDelaySec=10min systemd-analyze calendar '*-*-* 02:00:00' systemctl --user enable --now x.timer; loginctl enable-linger "$USER" # GitHub Actions: defaults.run.shell: bash → -eo pipefail # GitLab: resource_group: production; artifacts: when: always
| Symptom | Most likely cause | First command | Module |
|---|---|---|---|
| curl returns 0 but jq reports parse error | HTTP error page with no -f | curl -sS -D - -o /dev/null "$url" | 1 |
| rc=28 | Timeout (connect or total duration) | curl -w 'connect=%{time_connect} ttfb=%{time_starttransfer}' | 1 |
| Pagination loop / second page returns 400 | URL ends with \r | printf '%q\n' "$url" | 1 |
| Variable value contains quotes / brackets | az / aws output JSON | Add -o tsv / --output text | 2 |
| aws command hangs in CI | v2 paginator | export AWS_PAGER="" | 2 |
| loop only processes the first host | ssh consumed stdin | ssh -n | 3 |
| xargs rc=123 | at least one job failed | Check each job's .rc / joblog | 3 |
| current unchanged after switch | mv Missing -T | ls -lA "$(readlink -f current)" | 4 |
| Intermittent 404 during deploy | Non-atomic switch: delete first, then create | Switch to a temp link + mv -T | 4 |
| Half-written file in the backup directory | Writing directly to the final name | temp .part + mv | 5 |
| command not found in cron | Trim PATH | * * * * * env > /tmp/cron-env | 6 |
| Timer never fires | Only enabled the .service | systemctl --user list-timers --all | 6 |
| CI shows success despite a failure | No pipefail / || true | In YAML, add shell: bash | 7 |
| Process completed with exit code 141 | pipefail + SIGPIPE | use sed -n 1p instead of head -1 | 7 |
--connect-timeout 5 --max-time 60 --show-error --fail-with-body
In scripts, put -q (--disable), which ignores curlrc and keeps behavior predictable.
Host 10.0.* web-* api-* BatchMode yes ConnectTimeout 5 StrictHostKeyChecking accept-new ServerAliveInterval 15 ControlMaster auto ControlPath ~/.ssh/cm-%C ControlPersist 5m
You are responsible for a small internal service myapp (this lesson uses a static directory + python3 -m http.server instead). Release requirements: ① fetch the instance list from the “inventory API” (mockapi's /items, paginated), ② check each instance's health endpoint in parallel and abort if more than one fails; ③ back up the current release directory before deploying; ④ deploy the new version, with automatic rollback if the health check fails; ⑤ back up daily on a schedule; ⑥ run the smoke test in CI. Use opsctl v0.3 and this lesson's patterns for all steps.
~/bashlab/final.
mkdir -p ~/bashlab/final && cd ~/bashlab/final export PATH="$HOME/bashlab/opsctl/bin:$PATH"; opsctl version curl -fsS http://127.0.0.1:8000/healthz
api::get_all to fetch all 23 instances, save them as JSON Lines, and verify the count equals the response header X-Total-Count.
source ~/bashlab/final/api.sh # contains api::get_all (copied from Module 1)
api::get_all 'http://127.0.0.1:8000/items?per_page=10' > inventory.jsonl
want=$(curl -sS -o /dev/null -D - 'http://127.0.0.1:8000/items' | tr -d '\r' | awk -F': ' 'tolower($1)=="x-total-count"{print $2}')
got=$(wc -l < inventory.jsonl); [[ $got == "$want" ]] && echo "inventory complete: $got" || { echo "inventory incomplete $got/$want"; exit 1; }/status/503), using xargs -P 4 to call opsctl health -r 2 -t 2, writing each result to results/, count failures,and abort when failures > 1.
mkdir -p results
jq -r '.name' inventory.jsonl | head -6 | awk '{u = (NR==3) ? "/status/503" : "/healthz"; print $1 "\t" "http://127.0.0.1:8000" u}' > targets.tsv
tr '\t\n' '\0\0' < targets.tsv |
xargs -0 -n 2 -P 4 bash -c 'opsctl health -r 2 -t 2 "$2" 2>"results/$1.log"; echo $? > "results/$1.rc"' _
fails=$(grep -lvx 0 results/*.rc | wc -l); echo "failed instances: $fails"
((fails <= 1)) || { echo "too many failures, aborting release"; exit 1; }~/bashlab/deploy/current exists, back up the release directory it points to (opsctl backup -o ~/bashlab/final/predeploy -k 3 "$(readlink -f ~/bashlab/deploy/current)"), and verify it with sha256sum -c .--rollback once, then deploy 1.1.0 to restore it.opsctl-backup.timer (daily at 02:00 UTC, Persistent, random delay),systemd-analyze calendar and verify it; for environments without systemd, write an equivalent crontab (including flock and PATH).test/smoke.sh into GitHub Actions (shell: bash) or GitLab CI, deliberately make it fail once, and confirm the log artifacts are still uploaded.rm -rf ~/bashlab/final ~/bashlab/deploy; if no longer needed,systemctl --user disable --now opsctl-backup.timer.--retry?The built-in --retry only retries “transient errors” (timeouts, some 408/429/5xx responses), suits idempotent data fetches, and automatically honors Retry-After; health checks need to retry on any unexpected status code, log each attempt, add jitter, and let the caller (deploy) decide on rollback based on the result, so a hand-written loop fits better.
ln -sfn new .current.tmp && mv -Tf .current.tmp current the effect of each option.-s symbolic link; -f replace if it already exists; -n if the link name is a symlink to a directory, do not follow into it. mv -T treat the target as a regular file (otherwise it would move into the directory current points to); -f no prompt. Overall effect: prepare the new link under a temp name, then atomically replace the old one with a single rename(2).
If backups fail for a long time, age-based rotation gradually deletes all the old backups; count-based rotation always keeps the newest N. When compliance requires “retain no longer than X days” (for example, personal data), you need age-based deletion, and then you should pair it with monitoring of the “latest backup age”.
When the timer fires while the service unit is still active/activating, systemd does not start a second instance. This is usually good (it avoids contention), but if the job hangs and has no TimeoutStartSec, all later triggers are skipped, so you need a timeout and alerting.
pipe failures go unnoticed when no shell is set (no pipefail) || true and continue-on-error: true failures in background processes are not wait; the script exits early on the CI branch with exit 0.
CI: deploy (needs approval, auditing, and serialization), cloud resource checks (short-lived OIDC credentials), and smoke tests. Host: local backups and minute-level health checks (they need internal network access and should keep running when CI is down). The key point is one opsctl with two scheduling methods.
| Topic | Verified finding | Source (accessed 2026-11-17) |
|---|---|---|
| Latest curl version | 8.23.0 (2026-10-14) | GitHub curl/curl Releases |
| curl options and versions | --fail-with-body 7.76.0; --retry-all-errors 7.71.0; --json 7.82.0; --parallel 7.66.0 (default limit 50); %{header_json} 7.83.0; %header{} 7.84.0; %{num_retries} 8.9.0; %{exitcode}/%{errormsg} 7.75.0; --variable 8.3.0 | curl.se/docs/manpage.html |
| curl retry semantics | Transient errors: timeouts, FTP 4xx, HTTP 408/429/500/502/503/504/522/524; doubles from 1 second, capped at 10 minutes; Retry-After (7.66.0+); --retry-max-time no new retry starts after the deadline | Same as above (--retry and --retry-max-time entries) |
| curl exit codes | 22: HTTP ≥ 400 (-f); 28: timeout | Same as above (EXIT CODES) |
| Azure CLI | Latest 2.93.0 (2026-11-15); --query runs on the client side; read variable values using -o tsv | GitHub Azure/azure-cli · Troubleshooting Azure CLI · Query |
| AWS CLI v2 | Latest 2.40.4 (2026-11-16); return codes 0/1/2/130/252/253/254/255; for text output, paginate first, then run --query on each page | aws-cli CHANGELOG · Return codes · Filtering output |
| jq / yq / ShellCheck | jq 1.8.2; mikefarah yq v4.54.3; ShellCheck 0.11.0 | GitHub Releases: jqlang/jq, mikefarah/yq, koalaman/shellcheck |
| GNU parallel | Latest 20261022 | ftp.gnu.org/gnu/parallel |
| Bash | 5.3 is the current release; the Docker official image bash:5.3 (5.3.20, Alpine 3.24) is available | ftp.gnu.org/gnu/bash · Docker Hub bash |
| GitHub Actions shell | Not specified: bash -e {0}; bash: bash --noprofile --norc -eo pipefail {0}; sh: sh -e {0} | Workflow syntax |
| Actions versions | actions/checkout v7.0.1; actions/upload-artifact v7.0.2; azure/login v3.1.0; aws-actions/configure-aws-credentials v6.3.0 | GitHub Releases for each repository |
| GitLab CI script | A non-zero exit code fails the job and the following commands do not run; when joined into one string, only the last command is reported; commands containing colons need quotes | Scripts and job logs |
| rename(2) atomicity | if the new path already exists, it is atomically replaced | rename(2) |
| systemd timers | Persistent,RandomizedDelaySec,FixedRandomDelay; daily = 00:00 (tested on systemd 255) | systemd.timer(5) · systemd.time(7) |
The following was run for real on WSL2 Ubuntu 24.04.1 (Bash 5.2.21, curl 8.5.0, GNU coreutils 9.4, Python 3.12.3, systemd 255), with output labeled “Actual output”: all mockapi endpoints; curl's -f/--fail-with-body/--max-time/--retry/--retry-connrefused/%header{link}; %{num_retries} is unavailable in 8.5.0; Link pagination function; xargs parallelism and exit code 123; ssh-eats-stdin simulation; mv without -T errors; atomic switch vs delete-then-create (400 requests: 0 vs 132 404s); deploy.sh and the health/backup/deploy of opsctl v0.3; backup rotation, restore drills, lock conflicts, and corruption detection; systemd-analyze calendar; jq examples (Windows jq 1.6 invoked through WSL interop); az cloud list 's JMESPath queries (Azure CLI 2.84.0, not logged in).
All video links were verified via YouTube oEmbed (https://www.youtube.com/oembed?url=…&format=json) to check titles and channels (2026-11-17):
q_juztjhUlA mastering the curl command line - with Daniel Stenberg — Daniel StenbergI6id1Y0YuNk using curl better - with curl creator Daniel Stenberg — freeCodeCamp Talksw7-St22V1sA Rock-solid curl with Daniel Stenberg — Daniel Stenbergm9dhrq9iRHA The Ultimate JQ Tutorial: Everything You Need to Know to Parse JSON Like a Pro — EarthlyOpaiGYxkSuQ Part 1: GNU Parallel script processing and execution — Ole Tangerp7jLi_kgPg Xargs Should Be In Your Command Line Toolbag — DistroTubeI4EWvMFj37g Bash in 100 Seconds — Fireship8ga0xhZuG6k How To Write Bash Scripts In Linux - Complete Guide (Part 17 - Backup Script) — Learn Linux TVn6BuUgkZ5T0 Automate Your Tasks with systemd Timers: A Step-by-Step Guide — Learn Linux TV7cbP7fzn0D8 Linux Crash Course - Scheduling Tasks with Cron — Learn Linux TVv952m13p-b4 Cron Jobs For Beginners | Linux Task Scheduling — Akamai DevelopersR8_veQiYBjI GitHub Actions Tutorial - Basic Concepts and CI/CD Pipeline with Docker — TechWorld with NanaqP8kir2GUgo GitLab CI CD Tutorial for Beginners [Crash Course] — TechWorld with NanaNo verified video found for: the az / aws --query scripting, and atomic symlink-switch deployment — the corresponding modules provide storyboards instead. Video durations and publish dates were not checked one by one; the cards only describe their general nature.
The “Audio” tab uses the browser's built-in Web Speech API (speechSynthesis), preferring zh-CN voices to read the narration script and en-US voices for English terms. This lesson cannot embed MP3 files or generate video; the narration script and storyboard can be handed directly to a TTS / video tool.
ln -sfn is atomic on its own” depends on the implementation and version; this lesson did not verify it with strace, so the conservative advice is always to use “temp name + mv -T”.CRON_TZ 's support depends on the cron implementation; see man 5 crontab for details. Pre-installed software on GitHub-hosted runners is defined by the actions/runner-images manifest.util::retry uses full jitter, the “retrying in …s” in the actual output differs each time; PIDs, timestamps, and paths are values from the test environment.