TExcelTAD
Home › Automation Scripting: Bash, Python & Go › Mini Project: Inventory Health Report CLI

Mini Project: Inventory Health Report CLI

Time to put the course together in one tool, written twice. healthcheck reads a YAML inventory of services, checks each service's health endpoint, and prints a report. It is the kind of tool every operations team ends up writing: run by hand during an incident, by cron every few minutes, and by CI after a deploy.

Requirements:

Requirement From lesson
the inventory is YAML, linted and validated against a schema before use yamllint, JSON Schema Checks
options: --env, `--format table json, --timeout`
a check passes when the status matches and, if the endpoint returns JSON, its status field is ok Calling REST APIs
temporary failures (503, timeouts) are retried once with a short backoff Retries, Backoff and Pagination
exit status: 0 all healthy, 1 something unhealthy, 2 bad input Arguments, Usage and Exit Codes
JSON output for machines, a table for humans; logs on stderr jq in Scripts, Logging for Scripts

The Python version runs against an in-process fake transport and the Go version against httptest servers, so both are deterministic here; each section ends with the change that points it at the real network.

Step 1: the inventory, checked from the shell

The inventory lists each service's environment, URL, owner and, optionally, a different expected status. A real session lints it, lists what it contains, and converts it to JSON (which the Go version will read):

bash · try it yourself
cat > inventory.yaml <<'YAML'
# Services checked by healthcheck. Owned by the platform team.
defaults:
  timeout_seconds: 2
  expect_status: 200
services:
  - name: shop-api
    env: prod
    url: https://shop-api.example.com/healthz
    owner: team-core
  - name: checkout
    env: prod
    url: https://checkout.example.com/healthz
    owner: team-pay
  - name: search
    env: prod
    url: https://search.example.com/health
    owner: team-find
  - name: legacy-admin
    env: prod
    url: https://admin.example.com/
    owner: team-core
    expect_status: 302   # redirects to the login page when healthy
  - name: recommender
    env: prod
    url: https://reco.example.com/healthz
    owner: team-find
  - name: reports
    env: prod
    url: https://reports.example.com/healthz
    owner: team-data
  - name: shop-api
    env: staging
    url: https://shop-api.staging.example.com/healthz
    owner: team-core
YAML
yamllint -d '{extends: default, rules: {document-start: disable}}' inventory.yaml && echo "yamllint: ok"
echo "--- services per environment"
yq -o=json -I=0 '.services | group_by(.env) | map({"env": .[0].env, "count": length})' inventory.yaml
echo "--- prod services and owners"
yq '.services[] | select(.env == "prod") | .name + " (" + .owner + ")"' inventory.yaml
yq -o=json -I=0 '.' inventory.yaml > inventory.json
echo "--- converted for the Go version: $(jq '.services | length' inventory.json) services"
yamllint: ok
--- services per environment
[{"env":"prod","count":6},{"env":"staging","count":1}]
--- prod services and owners
shop-api (team-core)
checkout (team-pay)
search (team-find)
legacy-admin (team-core)
recommender (team-find)
reports (team-data)
--- converted for the Go version: 7 services

Step 2: the Python version

The program is organised in layers that you can test one at a time: load (parse and validate), check (one service, through a transport, with a retry), report (table or JSON), and main (arguments and exit status). The fake transport at the bottom plays six services in different states: healthy, failing with a 500, degraded (status 200 but "status": "degraded" in the body), healthy after one 503, slow enough to time out, and refusing connections.

python · try it yourself
import argparse
import json
import sys
from dataclasses import dataclass, asdict

import yaml
from jsonschema import Draft202012Validator

# ---------------------------------------------------------------- load
SCHEMA = {
    "type": "object",
    "required": ["services"],
    "properties": {
        "defaults": {"type": "object", "properties": {
            "timeout_seconds": {"type": "number", "exclusiveMinimum": 0},
            "expect_status": {"type": "integer"}}, "additionalProperties": False},
        "services": {"type": "array", "minItems": 1, "items": {
            "type": "object", "required": ["name", "env", "url", "owner"],
            "properties": {"name": {"type": "string"}, "env": {"enum": ["dev", "staging", "prod"]},
                           "url": {"type": "string", "pattern": "^https?://"}, "owner": {"type": "string"},
                           "expect_status": {"type": "integer"}},
            "additionalProperties": False}},
    },
    "additionalProperties": False,
}

class InputError(Exception):
    pass

def load_inventory(text):
    try:
        doc = yaml.safe_load(text)
    except yaml.YAMLError as e:
        raise InputError(f"inventory is not valid YAML: {e}") from e
    errors = [f"{'/'.join(map(str, e.path)) or '(root)'}: {e.message}"
              for e in Draft202012Validator(SCHEMA).iter_errors(doc)]
    if errors:
        raise InputError("inventory failed validation:\n  " + "\n  ".join(errors))
    defaults = {"timeout_seconds": 2, "expect_status": 200, **doc.get("defaults", {})}
    return [{**defaults, **svc} for svc in doc["services"]]

# ---------------------------------------------------------------- check
class ConnectionFailed(Exception):
    pass

@dataclass
class Result:
    name: str
    env: str
    owner: str
    healthy: bool
    detail: str
    attempts: int

def check(svc, transport, timeout, sleep, retries=1):
    for attempt in range(1, retries + 2):
        try:
            status, body = transport(svc["url"], timeout)
        except TimeoutError:
            outcome = (False, "timeout", True)
        except ConnectionFailed as e:
            outcome = (False, f"connection failed: {e}", False)
        else:
            if status != svc["expect_status"]:
                outcome = (False, f"HTTP {status}, want {svc['expect_status']}", status in (502, 503, 504))
            else:
                state = (json.loads(body).get("status", "ok") if body.startswith("{") else "ok")
                outcome = (state == "ok", f"HTTP {status}" + ("" if state == "ok" else f', status "{state}"'), False)
        healthy, detail, retryable = outcome
        if healthy or not retryable or attempt == retries + 1:
            return Result(svc["name"], svc["env"], svc["owner"], healthy, detail, attempt)
        sleep(0.5 * attempt)

# ---------------------------------------------------------------- report
def report(results, fmt, out):
    if fmt == "json":
        json.dump({"healthy": sum(r.healthy for r in results), "unhealthy": sum(not r.healthy for r in results),
                   "results": [asdict(r) for r in results]}, out, indent=2)
        out.write("\n")
        return
    out.write(f"{'SERVICE':14}{'OWNER':11}{'STATE':7}DETAIL\n")
    for r in sorted(results, key=lambda r: (r.healthy, r.name)):      # problems first
        retry = f" (after {r.attempts} attempts)" if r.attempts > 1 else ""
        out.write(f"{r.name:14}{r.owner:11}{'ok' if r.healthy else 'FAIL':7}{r.detail}{retry}\n")
    bad = sum(not r.healthy for r in results)
    out.write(f"{len(results) - bad} healthy, {bad} unhealthy\n")

# ---------------------------------------------------------------- main
def main(argv, inventory_text, transport, sleep, out=sys.stdout, err=sys.stdout):
    p = argparse.ArgumentParser(prog="healthcheck")
    p.add_argument("--env", default="prod", choices=["dev", "staging", "prod"])
    p.add_argument("--format", default="table", choices=["table", "json"])
    p.add_argument("--timeout", type=float, help="override the inventory's timeout (seconds)")
    args = p.parse_args(argv)
    try:
        services = [s for s in load_inventory(inventory_text) if s["env"] == args.env]
    except InputError as e:
        err.write(f"healthcheck: {e}\n")
        return 2
    results = [check(s, transport, args.timeout or s["timeout_seconds"], sleep) for s in services]
    report(results, args.format, out)
    return 0 if all(r.healthy for r in results) else 1

# ---------------------------------------------------------------- the fake network
def make_fake_transport():
    calls = {}
    def transport(url, timeout):
        host = url.split("/")[2]
        calls[host] = calls.get(host, 0) + 1
        if host == "shop-api.example.com":
            return 200, '{"status": "ok", "version": "1.4.2"}'
        if host == "checkout.example.com":
            return 500, '{"error": "database unavailable"}'
        if host == "search.example.com":
            return 200, '{"status": "degraded", "reason": "index rebuilding"}'
        if host == "admin.example.com":
            return 302, ""
        if host == "reco.example.com":
            return (503, "") if calls[host] == 1 else (200, '{"status": "ok"}')
        if host == "reports.example.com":
            raise TimeoutError()
        raise ConnectionFailed("connection refused")
    return transport

# inventory.yaml from step 1, inline because the browser has no files
INVENTORY = """
defaults: {timeout_seconds: 2, expect_status: 200}
services:
  - {name: shop-api,     env: prod,    url: "https://shop-api.example.com/healthz",         owner: team-core}
  - {name: checkout,     env: prod,    url: "https://checkout.example.com/healthz",         owner: team-pay}
  - {name: search,       env: prod,    url: "https://search.example.com/health",            owner: team-find}
  - {name: legacy-admin, env: prod,    url: "https://admin.example.com/",                   owner: team-core, expect_status: 302}
  - {name: recommender,  env: prod,    url: "https://reco.example.com/healthz",             owner: team-find}
  - {name: reports,      env: prod,    url: "https://reports.example.com/healthz",          owner: team-data}
  - {name: shop-api,     env: staging, url: "https://shop-api.staging.example.com/healthz", owner: team-core}
"""

waits = []
print("$ healthcheck --env prod")
print("-> exit", main(["--env", "prod"], INVENTORY, make_fake_transport(), waits.append))
print("waited (retries):", waits)
print()
print("$ healthcheck --env staging --format json")
print("-> exit", main(["--env", "staging", "--format", "json"], INVENTORY, make_fake_transport(), waits.append))
print()
print("$ healthcheck  (with a broken inventory)")
broken = INVENTORY.replace("env: staging", "env: stagin").replace('"https://admin', '"admin')
print("-> exit", main([], broken, make_fake_transport(), waits.append))
$ healthcheck --env prod
SERVICE       OWNER      STATE  DETAIL
checkout      team-pay   FAIL   HTTP 500, want 200
reports       team-data  FAIL   timeout (after 2 attempts)
search        team-find  FAIL   HTTP 200, status "degraded"
legacy-admin  team-core  ok     HTTP 302
recommender   team-find  ok     HTTP 200 (after 2 attempts)
shop-api      team-core  ok     HTTP 200
3 healthy, 3 unhealthy
-> exit 1
waited (retries): [0.5, 0.5]

$ healthcheck --env staging --format json
{
  "healthy": 0,
  "unhealthy": 1,
  "results": [
    {
      "name": "shop-api",
      "env": "staging",
      "owner": "team-core",
      "healthy": false,
      "detail": "connection failed: connection refused",
      "attempts": 1
    }
  ]
}
-> exit 1

$ healthcheck  (with a broken inventory)
healthcheck: inventory failed validation:
  services/3/url: 'admin.example.com/' does not match '^https?://'
  services/6/env: 'stagin' is not one of ['dev', 'staging', 'prod']
-> exit 2

Things to notice:

  • The degraded search service returned HTTP 200 and still failed: checking the body catches a service that answers but is not working.
  • recommender failed once with 503 and passed on the retry; checkout's 500 was not retried (a 500 from a health endpoint usually means "broken", not "busy"), and neither was the refused connection.
  • The table puts problems first, sorted by name, so the important lines are at the top of a long report.
  • The broken inventory was rejected with exit status 2 and every problem listed, before a single request was sent.

Pointing it at the real network

Replace the fake with a real transport (and sleep with time.sleep), read the inventory from a file, and send errors to stderr:

python
import os, time, urllib.error, urllib.request

class NoRedirect(urllib.request.HTTPRedirectHandler):
    def redirect_request(self, *args, **kwargs):
        return None                                            # urllib then raises HTTPError(302)

def urllib_transport(url, timeout):
    req = urllib.request.Request(url, headers={"User-Agent": "healthcheck/1.0"})
    opener = urllib.request.build_opener(NoRedirect)           # report 302 as 302 instead of following it
    try:
        with opener.open(req, timeout=timeout) as resp:
            return resp.status, resp.read(65536).decode("utf-8", "replace")
    except urllib.error.HTTPError as e:                        # 3xx/4xx/5xx: an answer, not a failure
        return e.code, e.read(65536).decode("utf-8", "replace")
    except TimeoutError:
        raise
    except urllib.error.URLError as e:
        if isinstance(e.reason, TimeoutError):
            raise TimeoutError() from e
        raise ConnectionFailed(str(e.reason)) from e

if __name__ == "__main__":
    with open(os.environ.get("HEALTHCHECK_INVENTORY", "inventory.yaml")) as f:
        sys.exit(main(sys.argv[1:], f.read(), urllib_transport, time.sleep, err=sys.stderr))

On a real network you would also check services in parallel: concurrent.futures.ThreadPoolExecutor(max_workers=8) with pool.map(lambda s: check(s, …), services) keeps the results in input order. (Pyodide has no threads, which is why the browser version is sequential.)

Step 3: the Go version

The Go version reads the JSON that yq produced in step 1 (Go's standard library has no YAML parser), parses its flags from a fixed argument list, and checks services concurrently with a limit. One httptest server plays all the services, routed by the Host header, and a custom dialer sends every hostname to it; the client code is exactly what would run against the real hosts:

go · try it yourself
package main

import (
	"context"
	"encoding/json"
	"errors"
	"flag"
	"fmt"
	"io"
	"net"
	"net/http"
	"net/http/httptest"
	"os"
	"sort"
	"strings"
	"sync"
	"sync/atomic"
	"syscall"
	"time"
)

// ---- load -------------------------------------------------------------------------------
type Service struct {
	Name         string `json:"name"`
	Env          string `json:"env"`
	URL          string `json:"url"`
	Owner        string `json:"owner"`
	ExpectStatus int    `json:"expect_status"`
}

type Inventory struct {
	Defaults struct {
		TimeoutSeconds float64 `json:"timeout_seconds"`
		ExpectStatus   int     `json:"expect_status"`
	} `json:"defaults"`
	Services []Service `json:"services"`
}

func loadInventory(r io.Reader) (Inventory, error) {
	var inv Inventory
	dec := json.NewDecoder(r)
	dec.DisallowUnknownFields()
	if err := dec.Decode(&inv); err != nil {
		return inv, fmt.Errorf("inventory: %w", err)
	}
	if len(inv.Services) == 0 {
		return inv, errors.New("inventory: no services")
	}
	for i := range inv.Services {
		s := &inv.Services[i]
		if s.Name == "" || !strings.HasPrefix(s.URL, "http") {
			return inv, fmt.Errorf("inventory: service %d: name and an http(s) url are required", i)
		}
		if s.ExpectStatus == 0 {
			s.ExpectStatus = inv.Defaults.ExpectStatus
		}
	}
	return inv, nil
}

// ---- check ------------------------------------------------------------------------------
type Result struct {
	Name     string `json:"name"`
	Env      string `json:"env"`
	Owner    string `json:"owner"`
	Healthy  bool   `json:"healthy"`
	Detail   string `json:"detail"`
	Attempts int    `json:"attempts"`
}

func checkOnce(ctx context.Context, client *http.Client, s Service) (ok bool, detail string, retry bool) {
	req, err := http.NewRequestWithContext(ctx, http.MethodGet, s.URL, nil)
	if err != nil {
		return false, err.Error(), false
	}
	req.Header.Set("User-Agent", "healthcheck/1.0")
	resp, err := client.Do(req)
	var nerr net.Error
	switch {
	case errors.As(err, &nerr) && nerr.Timeout():
		return false, "timeout", true
	case errors.Is(err, syscall.ECONNREFUSED):
		return false, "connection failed: connection refused", false
	case err != nil:
		return false, "connection failed", false
	}
	defer resp.Body.Close()
	if resp.StatusCode != s.ExpectStatus {
		return false, fmt.Sprintf("HTTP %d, want %d", resp.StatusCode, s.ExpectStatus),
			resp.StatusCode == 502 || resp.StatusCode == 503 || resp.StatusCode == 504
	}
	var body struct {
		Status string `json:"status"`
	}
	if strings.HasPrefix(resp.Header.Get("Content-Type"), "application/json") {
		json.NewDecoder(io.LimitReader(resp.Body, 65536)).Decode(&body)
	}
	if body.Status != "" && body.Status != "ok" {
		return false, fmt.Sprintf("HTTP %d, status %q", resp.StatusCode, body.Status), false
	}
	return true, fmt.Sprintf("HTTP %d", resp.StatusCode), false
}

func check(ctx context.Context, client *http.Client, s Service) Result {
	for attempt := 1; ; attempt++ {
		ok, detail, retry := checkOnce(ctx, client, s)
		if ok || !retry || attempt == 2 {
			return Result{s.Name, s.Env, s.Owner, ok, detail, attempt}
		}
		time.Sleep(50 * time.Millisecond)
	}
}

func checkAll(client *http.Client, services []Service, limit int) []Result {
	results := make([]Result, len(services))
	sem := make(chan struct{}, limit)
	var wg sync.WaitGroup
	for i, s := range services {
		wg.Add(1)
		go func() {
			defer wg.Done()
			sem <- struct{}{}
			defer func() { <-sem }()
			results[i] = check(context.Background(), client, s)
		}()
	}
	wg.Wait()
	return results
}

// ---- report and run -----------------------------------------------------------------------
func run(args []string, inventory io.Reader, client *http.Client, out io.Writer) int {
	fs := flag.NewFlagSet("healthcheck", flag.ContinueOnError)
	fs.SetOutput(out)
	env := fs.String("env", "prod", "environment to check")
	format := fs.String("format", "table", "table or json")
	if err := fs.Parse(args); err != nil {
		return 2
	}
	inv, err := loadInventory(inventory)
	if err != nil {
		fmt.Fprintln(out, "healthcheck:", err)
		return 2
	}
	if client.Timeout == 0 {
		client.Timeout = time.Duration(inv.Defaults.TimeoutSeconds * float64(time.Second))
	}
	var selected []Service
	for _, s := range inv.Services {
		if s.Env == *env {
			selected = append(selected, s)
		}
	}
	results := checkAll(client, selected, 4)
	bad := 0
	for _, r := range results {
		if !r.Healthy {
			bad++
		}
	}
	if *format == "json" {
		enc := json.NewEncoder(out)
		enc.SetIndent("", "  ")
		enc.Encode(struct {
			Healthy   int      `json:"healthy"`
			Unhealthy int      `json:"unhealthy"`
			Results   []Result `json:"results"`
		}{len(results) - bad, bad, results})
	} else {
		sort.SliceStable(results, func(a, b int) bool {
			if results[a].Healthy != results[b].Healthy {
				return !results[a].Healthy // problems first
			}
			return results[a].Name < results[b].Name
		})
		fmt.Fprintf(out, "%-14s%-11s%-7s%s\n", "SERVICE", "OWNER", "STATE", "DETAIL")
		for _, r := range results {
			state, retry := "ok", ""
			if !r.Healthy {
				state = "FAIL"
			}
			if r.Attempts > 1 {
				retry = fmt.Sprintf(" (after %d attempts)", r.Attempts)
			}
			fmt.Fprintf(out, "%-14s%-11s%-7s%s%s\n", r.Name, r.Owner, state, r.Detail, retry)
		}
		fmt.Fprintf(out, "%d healthy, %d unhealthy\n", len(results)-bad, bad)
	}
	if bad > 0 {
		return 1
	}
	return 0
}

// ---- the fake network ----------------------------------------------------------------------
// inventory.json as written by yq in step 1 (shortened to the fields the tool reads)
const inventoryJSON = `{"defaults": {"timeout_seconds": 0.3, "expect_status": 200}, "services": [
 {"name": "shop-api", "env": "prod", "url": "http://shop-api.example.com/healthz", "owner": "team-core"},
 {"name": "checkout", "env": "prod", "url": "http://checkout.example.com/healthz", "owner": "team-pay"},
 {"name": "search", "env": "prod", "url": "http://search.example.com/health", "owner": "team-find"},
 {"name": "legacy-admin", "env": "prod", "url": "http://admin.example.com/", "owner": "team-core", "expect_status": 302},
 {"name": "recommender", "env": "prod", "url": "http://reco.example.com/healthz", "owner": "team-find"},
 {"name": "reports", "env": "prod", "url": "http://reports.example.com/healthz", "owner": "team-data"},
 {"name": "shop-api", "env": "staging", "url": "http://shop-api.staging.example.com/healthz", "owner": "team-core"}]}`

func fakeNetwork() (*http.Client, func()) {
	var recoCalls atomic.Int32
	srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		jsonReply := func(code int, body string) {
			w.Header().Set("Content-Type", "application/json")
			w.WriteHeader(code)
			fmt.Fprint(w, body)
		}
		switch r.Host {
		case "shop-api.example.com":
			jsonReply(200, `{"status": "ok", "version": "1.4.2"}`)
		case "checkout.example.com":
			jsonReply(500, `{"error": "database unavailable"}`)
		case "search.example.com":
			jsonReply(200, `{"status": "degraded", "reason": "index rebuilding"}`)
		case "admin.example.com":
			http.Redirect(w, r, "/login", http.StatusFound)
		case "reco.example.com":
			if recoCalls.Add(1) == 1 {
				w.WriteHeader(503)
				return
			}
			jsonReply(200, `{"status": "ok"}`)
		case "reports.example.com":
			select { // slower than the timeout
			case <-time.After(2 * time.Second):
			case <-r.Context().Done():
			}
		default:
			jsonReply(404, `{"error": "unknown host"}`)
		}
	}))
	gone := httptest.NewServer(nil)
	goneAddr := gone.Listener.Addr().String()
	gone.Close() // nothing listens here any more: connections are refused
	transport := &http.Transport{DialContext: func(ctx context.Context, network, hostport string) (net.Conn, error) {
		target := srv.Listener.Addr().String() // every host resolves to the test server...
		if strings.HasPrefix(hostport, "shop-api.staging.") {
			target = goneAddr // ...except staging, which is down
		}
		return (&net.Dialer{}).DialContext(ctx, network, target)
	}}
	client := &http.Client{
		Transport: transport,
		// report redirects instead of following them, like `curl` without -L
		CheckRedirect: func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse },
	}
	return client, srv.Close
}

func main() {
	for _, args := range [][]string{{"-env", "prod"}, {"-env", "staging", "-format", "json"}} {
		client, stop := fakeNetwork()
		fmt.Println("$ healthcheck", strings.Join(args, " "))
		code := run(args, strings.NewReader(inventoryJSON), client, os.Stdout)
		fmt.Println("-> exit", code)
		stop()
	}
	client, stop := fakeNetwork()
	defer stop()
	fmt.Println("$ healthcheck  (with a broken inventory)")
	broken := strings.Replace(inventoryJSON, `"owner": "team-pay"`, `"owner": "team-pay", "ower": "x"`, 1)
	fmt.Println("-> exit", run(nil, strings.NewReader(broken), client, os.Stdout))
}
$ healthcheck -env prod
SERVICE       OWNER      STATE  DETAIL
checkout      team-pay   FAIL   HTTP 500, want 200
reports       team-data  FAIL   timeout (after 2 attempts)
search        team-find  FAIL   HTTP 200, status "degraded"
legacy-admin  team-core  ok     HTTP 302
recommender   team-find  ok     HTTP 200 (after 2 attempts)
shop-api      team-core  ok     HTTP 200
3 healthy, 3 unhealthy
-> exit 1
$ healthcheck -env staging -format json
{
  "healthy": 0,
  "unhealthy": 1,
  "results": [
    {
      "name": "shop-api",
      "env": "staging",
      "owner": "team-core",
      "healthy": false,
      "detail": "connection failed: connection refused",
      "attempts": 1
    }
  ]
}
-> exit 1
$ healthcheck  (with a broken inventory)
healthcheck: inventory: json: unknown field "ower"
-> exit 2

The report is the same as Python's, line for line, even though the checks ran concurrently: results are stored by index and sorted before printing. The timeout is 0.3 s here so the slow reports service fails quickly.

Pointing it at the real network

Delete fakeNetwork, open the inventory file, and build a normal client (errors go to stderr in the real tool):

go
func main() {
	path := os.Getenv("HEALTHCHECK_INVENTORY") // same convention as the Python version
	if path == "" {
		path = "inventory.json" // YAML converted with: yq -o=json inventory.yaml > inventory.json
	}
	f, err := os.Open(path)
	if err != nil {
		fmt.Fprintln(os.Stderr, "healthcheck:", err)
		os.Exit(2)
	}
	defer f.Close()
	client := &http.Client{CheckRedirect: func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse }}
	code := run(os.Args[1:], f, client, os.Stdout)
	f.Close() // os.Exit skips deferred calls
	os.Exit(code)
}

To read the YAML directly, add go.yaml.in/yaml/v3 (go get go.yaml.in/yaml/v3), give the structs yaml:"…" tags next to the json:"…" ones, and call yaml.NewDecoder(r).Decode(&inv) (call KnownFields(true) on the decoder for the same strictness as DisallowUnknownFields). Build and ship it as in Why Go for Tooling: CGO_ENABLED=0 go build -trimpath -o healthcheck .

Step 4: wire it into automation

bash
# cron: every 5 minutes, alert only on failure (exit 1) or bad input (exit 2)
*/5 * * * * flock -n /run/healthcheck.lock /usr/local/bin/healthcheck --env prod --format json \
            > /var/lib/healthcheck/last.json 2>> /var/log/healthcheck.err || /usr/local/bin/page-oncall healthcheck

# CI, after a deploy: fail the pipeline if the new version is unhealthy
healthcheck --env staging --format json | tee health.json
jq -e '.unhealthy == 0' health.json > /dev/null

Extend it

  1. Add --only NAME (repeatable) and --owner TEAM filters, with tests that call main/run directly.
  2. Add a --min-healthy-percent threshold so a single flaky service in a large fleet returns 0 with a warning.
  3. Record latency per check and print it in the table (round it, or the output stops being deterministic in tests).
  4. Generate the inventory from an API instead of a file, with the paginated client from Retries, Backoff and Pagination.
  5. Turn the Go version into a long-running exporter that serves the results as Prometheus metrics, the bridge into the Observability course.

Test yourself

Why does the tool check the JSON body as well as the status code?

  1. Status codes are unreliable
  2. A service can answer 200 while reporting itself degraded; reading the body catches it
  3. JSON is faster to parse
  4. To measure latency

Which exit status does healthcheck return for an inventory that fails validation?

  1. 0
  2. 1
  3. 2
  4. It crashes with a traceback

How does the Go version keep its output identical to the sequential Python version while checking in parallel?

  1. It checks one service at a time
  2. Results are written to index slots and sorted before printing
  3. It uses a mutex around fmt.Printf
  4. Goroutines finish in order