04 / RELIABLE ADMINISTRATION TOOLS · LESSON 14

Reuse health-check functions

Compose a report around a trusted helper instead of duplicating its policy.

16 min · learn at your pace

Separate policy from presentation

A small helper can decide whether a memory observation needs attention, while the calling script handles file iteration and report layout. This separation makes a policy change easier to review and reuse across several tools.

The repository-supplied lib/health.sh defines classify_memory. It accepts one validated integer and prints a state. Source that trusted code explicitly with source ./lib/health.sh; this is different from sourcing an inventory or a user-editable policy file. Only code you intend to execute belongs at that boundary.

Treat the helper as an interface

Call the helper for each inventory row and carry its returned state into the report. Do not reproduce its threshold in the caller, or a later library update will leave two inconsistent rules. A future helper may return unknown when the available measurement cannot support a decision; the caller should preserve that label.

Put the per-asset report logic in a function with clear arguments and local variables. Quoted expansions preserve an asset ID as one value, and a constant printf format keeps output stable. Functions in this course remain Bash 3.2-compatible; associative data structures, when needed, belong to awk rather than newer Bash-only features.

Try an example.sh
source ./lib/health.sh
printf '4 GiB: %s\n' "$(classify_memory 4)"
YOUR TURN

Put it into practice.

Source the trusted lib/health.sh and call classify_memory with each memory_gib value from validated inventory.tsv. The helper prints a state (ok, review or unknown) and returns success. Print asset_id<TAB>memory_gib<TAB>state in inventory order, preserving the helper’s result. Use a reusable per-asset reporting function. The checker replaces the helper to confirm the caller follows its interface rather than copying the current threshold.

See an explained solution
One way to solve it.sh
source ./lib/health.sh || exit 1
report_asset() {
 local id=$1 memory=$2 state
 state=$(classify_memory "$memory") || return 1
 printf '%s\t%s\t%s\n' "$id" "$memory" "$state"
}
printf 'asset_id\tmemory_gib\tstate\n'
while IFS=$'\t' read -r id hostname role memory;do
 [ "$id" = asset_id ] && continue
 report_asset "$id" "$memory" || exit 1
done < inventory.tsv

The caller delegates policy to the supplied library and owns only iteration and presentation. A local-variable reporting function keeps each row’s values separate, and library substitutions prove that a policy update is honoured.