{"guides":[],"hints":[{"hint":"Approval and test evidence refer to specific bytes.","lessonID":"devops.delivery-artifacts","nuance":"Tie trusted verification and approval to the exact artifact digest. A mutable tag, a source commit or a self-reported success flag is not equivalent evidence."},{"hint":"Measure a repeatable outcome and retain failure/recovery evidence.","lessonID":"devops.delivery-loop","nuance":"A useful automation reduces repeated manual work while keeping changes bounded, observable and recoverable; its command count is not the success criterion."},{"hint":"Retain the record that connects intent to real objects.","lessonID":"devops.iac-state","nuance":"Locking coordinates cooperating writers; it does not prove that an apply is safe or that external drift cannot happen."},{"hint":"Separate who may assume the role from what the role may do.","lessonID":"devops.iam-boundaries","nuance":"An identity can authenticate successfully and still be denied a resource action. Test that denial deliberately."},{"hint":"Track the writer boundary and where later acknowledged work lives.","lessonID":"devops.incident-recovery","nuance":"Rehearse restoration in isolation and preserve/reconcile later accepted writes. Binary compatibility, persistent-data recovery and route verification are separate obligations."},{"hint":"Separate name resolution from the connection and application contract.","lessonID":"devops.network-evidence","nuance":"Repeatedly testing from a different environment can hide the original failure. Preserve the caller and verify the failing boundary."},{"hint":"The plan is evidence about a particular observation.","lessonID":"devops.reconciliation","nuance":"A stale plan must be rejected and regenerated from a fresh observation. Use server-side preconditions; client-side checks alone cannot prevent a concurrent write."},{"hint":"Validate at the boundary, before any side effect.","lessonID":"devops.safe-cli","nuance":"Reject unknown input and apply independent byte, target, concurrency and time budgets. Validate and test a dry run before introducing writes."},{"hint":"A ratio needs a valid, meaningful denominator.","lessonID":"devops.slo-burn","nuance":"No observations mean missing evidence, not demonstrated health. Define eligible events and require appropriate sustained and recent signals before alerting."},{"hint":"Count arguments after expansion, especially when a path contains spaces.","lessonID":"operations.bash-arguments","nuance":"Avoiding a shell prevents shell reinterpretation; the invoked tool still needs an allowed-operation contract."},{"hint":"Check which command supplies the pipeline's status before trusting its output.","lessonID":"operations.bash-failures","nuance":"set -e has contextual exceptions; an explicit failure branch is often easier to reason about."},{"hint":"Names and content identities are different.","lessonID":"operations.container-registry","nuance":"A digest identifies content; platform compatibility and pull authorization still need verification."},{"hint":"List the runtime files before choosing scratch as a base image.","lessonID":"operations.docker-build","nuance":"A static executable may still need certificates, configuration, zoneinfo or writable storage."},{"hint":"Each container has its own loopback address.","lessonID":"operations.docker-compose","nuance":"A startup health check is not a guarantee of future dependency availability."},{"hint":"Image metadata is different from host networking.","lessonID":"operations.docker-run","nuance":"The answer is no: publication requires an explicit runtime networking configuration."},{"hint":"A volume has its own lifecycle.","lessonID":"operations.docker-volumes","nuance":"Surviving replacement does not protect a volume against host loss or deliberate deletion."},{"hint":"The staging area is the next snapshot.","lessonID":"operations.git-local","nuance":"git restore --staged preserves the working file; plain git restore can replace it."},{"hint":"Fetch and integration are separate operations.","lessonID":"operations.git-remotes","nuance":"A rejected push should lead to comparison, not an automatic forced history rewrite."},{"hint":"Check the resulting dependency diff.","lessonID":"operations.go-tooling","nuance":"A race check covers executed paths and supported native targets, not every possible schedule."},{"hint":"A transport success can still carry an HTTP error.","lessonID":"operations.http-debugging","nuance":"Do not assume curl exit status zero means the application returned HTTP 200."},{"hint":"A visible difference is an intended diff outcome.","lessonID":"operations.kubernetes-apply","nuance":"Dry-run validates a request but does not test image availability or scheduling."},{"hint":"A running process keeps its environment.","lessonID":"operations.kubernetes-config","nuance":"Base64 is an encoding, not encryption or an access-control policy."},{"hint":"A context includes the cluster and user identity.","lessonID":"operations.kubernetes-contexts","nuance":"Authorization and reachability are separate checks; a context name alone is not proof of the intended server."},{"hint":"A restarted container has a previous instance.","lessonID":"operations.kubernetes-inspect","nuance":"Container logs and events have retention limits; use centralized collection for durable history."},{"hint":"The local forwarding process has a lifetime.","lessonID":"operations.kubernetes-network","nuance":"A tunnel request can succeed while the normal network-policy path still fails."},{"hint":"A Deployment revision tracks its workload template.","lessonID":"operations.kubernetes-rollout","nuance":"History retention and backward-compatible data changes determine whether rollback can succeed."},{"hint":"Trace Deployment selector, Pod label and Service selector together.","lessonID":"operations.kubernetes-workloads","nuance":"Scaling replicas also scales their downstream connection pools and worker pressure."},{"hint":"Unit configuration and process lifetime are separate.","lessonID":"operations.linux-service","nuance":"The service manager can report active while the application endpoint is failing."},{"hint":"Identify whether an address belongs to the container, the VM or the host.","lessonID":"operations.podman-runtime","nuance":"Rootless containers still need explicit resource, filesystem and network policies."},{"hint":"For each health failure, name the action the platform should take.","lessonID":"operations.probes-and-shutdown","nuance":"Use a fresh bounded drain context; the signal context is already canceled when shutdown starts."},{"hint":"Relative paths begin at the current working directory.","lessonID":"operations.shell-files","nuance":"cd affects its own shell; another terminal can be in a different directory."},{"hint":"Background work still has an outcome.","lessonID":"operations.shell-processes","nuance":"A PID can be reused after exit; keep ownership instead of targeting processes by vague names."},{"hint":"A child receives an environment when it starts.","lessonID":"operations.shell-scripts","nuance":"Configuration is not automatically secret; command traces and logs can reveal it."},{"hint":"uniq compares neighboring lines.","lessonID":"operations.shell-text","nuance":"Do not confuse exact-line counts with rates from timestamped structured logs."}],"id":"devops","labs":[{"checks":[{"description":"The configuration has the required port and mode.","equals":"PORT=8080\nMODE=dev\n","path":"service.env"},{"description":"The original README is preserved.","equals":"Private training files. No production credentials.\n","path":"README.txt"}],"id":"files-contract","initialFiles":{"README.txt":"Private training files. No production credentials.\n"},"instructions":"Write service.env with PORT=8080 and MODE=dev on separate lines. Inspect it with cat. Run help to see the available commands. Files in this lab persist between runs.","objective":"Create and inspect a configuration without changing another file.","starter":"printf 'PORT=8080\\nMODE=dev\\n' > service.env\ncat service.env","title":"Files and configuration"},{"checks":[{"description":"The two distinct error records are present in sorted order.","equals":"ERROR bad-token\nERROR timeout\n","path":"errors.txt"}],"id":"logs-pipeline","initialFiles":{"logs/service.log":"INFO start\nERROR timeout\nERROR bad-token\nERROR timeout\n"},"instructions":"Read logs/service.log. Select ERROR records, sort and deduplicate them into errors.txt. Confirm the result with cat or wc -l. grep matches literal substrings here, without regular-expression flags.","objective":"Filter and deduplicate real log records through a bounded pipeline.","starter":"grep ERROR logs/service.log | sort | uniq > errors.txt\ncat errors.txt","title":"Investigate service logs"},{"checks":[{"description":"The promoted artifact matches its original source.","path":"release/app.conf","sameAs":"src/app.conf"},{"description":"The recorded digest describes the promoted bytes.","path":"release/digest.txt","sha256Of":"release/app.conf"}],"id":"artifact-digest","initialFiles":{"release/README.txt":"Release directory\n","src/app.conf":"MODE=prod\nPORT=8080\n"},"instructions":"Copy src/app.conf to release/app.conf, then record its sha256sum in release/digest.txt. This command emits a digest only. The lab checks the actual bytes and digest independently.","objective":"Copy the same artifact and record a digest of the delivered bytes.","starter":"cp src/app.conf release/app.conf\nsha256sum release/app.conf > release/digest.txt\ncat release/digest.txt","title":"Promote an artifact by digest"},{"checks":[{"description":"The readiness gate recorded healthy.","equals":"healthy\n","path":"rollout.txt"}],"id":"readiness-gate","initialFiles":{"health/README.txt":"Create ready.flag only after the local contract is satisfied.\n"},"instructions":"Run the starter before creating a ready flag: it should write blocked. Then create health/ready.flag and run the gate again. A real deployment also needs a fresh response from the actual target; this local file contract does not claim a Kubernetes rollout.","objective":"Distinguish a blocked gate from a passing one using actual lab state.","starter":"if test -f health/ready.flag; then\n  echo healthy > rollout.txt\nelse\n  echo blocked > rollout.txt\nfi\ncat rollout.txt","title":"Gate a rollout on readiness"},{"checks":[{"description":"The live configuration matches the original backup.","path":"live/settings.conf","sameAs":"backups/settings.conf"},{"description":"All accepted writes remain intact.","equals":"write-100\nwrite-101\nwrite-102\n","path":"live/accepted-writes.log"}],"id":"restore-with-writes","initialFiles":{"backups/settings.conf":"MODE=prod\n","live/accepted-writes.log":"write-100\nwrite-101\nwrite-102\n","live/settings.conf":"MODE=unsafe\n"},"instructions":"Inspect live/settings.conf and backups/settings.conf. Restore only the configuration. Preserve live/accepted-writes.log byte-for-byte. This is a local restore rehearsal, not proof of a database point-in-time recovery.","objective":"Restore the faulty configuration while retaining accepted data.","starter":"cat live/settings.conf\ncat backups/settings.conf\n# Restore only the configuration, then inspect accepted writes.","title":"Recover configuration, preserve writes"},{"checks":[{"description":"The artifact matches the original source.","path":"release/app.conf","sameAs":"src/app.conf"},{"description":"The verification script recorded the production contract.","equals":"MODE=prod\n","path":"evidence.txt"},{"description":"The digest matches the delivered artifact.","path":"release/digest.txt","sha256Of":"release/app.conf"}],"id":"ci-evidence","initialFiles":{"release/README.txt":"Promotion target\n","src/app.conf":"MODE=prod\nPORT=8080\n","verify.sh":"test -f release/app.conf && grep MODE=prod release/app.conf > evidence.txt && sha256sum release/app.conf > release/digest.txt\n"},"instructions":"Inspect verify.sh, then run it before promotion and observe failure. Copy the production configuration to release/app.conf and run sh verify.sh again. The checks inspect evidence.txt and the delivered digest. This shell has no cloud runners or credentials.","objective":"Run a real local script and inspect its evidence and exit status.","starter":"cat verify.sh\nsh verify.sh","title":"A repeatable verification script"}],"practice":{"bugs":[],"drills":[],"interviews":[],"quizzes":[],"reviewPairs":[],"reviewRounds":[]},"readings":[{"conceptTag":"tooling.bash","hint":"Relative paths begin at the current working directory.","id":"operations.shell-files","introduction":"A shell starts in a working directory, and relative paths are resolved there. Before building or moving files, establish that location. These exercises use a new scratch directory on your own Mac or Linux machine; no administrator permissions are needed.","nuance":"cd affects its own shell; another terminal can be in a different directory.","objective":"Use pwd, cd, ls, mkdir, cp and mv in a small disposable workspace.","question":"What does pwd show?","references":["https://www.gnu.org/software/bash/manual/bash.html#Bourne-Shell-Builtins","https://www.gnu.org/software/coreutils/manual/coreutils.html"],"reviewAnswer":"Prints the current working directory","reviewPrompt":"Bash pwd","sections":[{"body":"pwd prints the working directory; ls -la includes hidden entries and metadata. cd changes this shell, not every terminal. The home shortcut is expanded by the shell, while a quoted path can contain spaces.","code":"pwd\nls -la\ncd \"$HOME\"\npwd","language":"bash","title":"Locate the project before changing it","walkthrough":"Compare the two pwd results. ls -la may show .git, but that alone does not establish a repository root. Quoting \"$HOME\" passes a single path, even if it contains spaces."},{"body":"mktemp -d makes a unique scratch directory. mkdir -p creates missing directory components. cp copies bytes; mv changes the path. Keep the original until you have inspected the destination rather than experimenting on project files.","code":"scratch_dir=$(mktemp -d)\nmkdir -p \"$scratch_dir/input\" \"$scratch_dir/output\"\nprintf \"%s\\n\" \"hello Go\" > \"$scratch_dir/input/note.txt\"\ncp \"$scratch_dir/input/note.txt\" \"$scratch_dir/output/copy.txt\"\nmv \"$scratch_dir/output/copy.txt\" \"$scratch_dir/output/result.txt\"\ncat \"$scratch_dir/output/result.txt\"","language":"bash","title":"Create and copy a small fixture","walkthrough":"The final line prints hello Go. The > operator creates or truncates the named file; it is appropriate here because the fixture is new. The scratch path stays in scratch_dir for the next command."},{"body":"wc -l counts newline-terminated lines, and cmp compares the copied content. rm removes the specifically named fixture files; rmdir removes only empty directories, making an unexpected leftover visible instead of recursively erasing it.","code":"wc -l \"$scratch_dir/output/result.txt\"\ncmp \"$scratch_dir/input/note.txt\" \"$scratch_dir/output/result.txt\"\nrm \"$scratch_dir/input/note.txt\" \"$scratch_dir/output/result.txt\"\nrmdir \"$scratch_dir/input\" \"$scratch_dir/output\" \"$scratch_dir\"","language":"bash","title":"Check the result and remove only the fixture","walkthrough":"wc should report one line. cmp is silent with status zero for identical files. The cleanup names only files this exercise created; rmdir fails if another file remains, so inspect rather than adding recursive deletion."}],"takeaway":"Start by checking the working directory, quote paths, and verify copied bytes before removing anything. Practice filesystem changes in a named scratch workspace, not in your only project copy.","title":"Bash essentials: navigate, inspect and copy files","unitID":"operations","wrongAnswers":["Every file under your home directory","The path of the Go compiler executable"]},{"conceptTag":"tooling.bash","hint":"uniq compares neighboring lines.","id":"operations.shell-text","introduction":"Most development investigations begin with a filename, a symbol or a short log fragment. Use small commands to narrow the evidence before opening a huge file. The examples assume you are in a trusted Go project and have a text application log named app.log.","nuance":"Do not confuse exact-line counts with rates from timestamped structured logs.","objective":"Combine find, grep, head, tail, sort and uniq without hiding their exit behavior.","question":"Why does counting repeated lines usually sort before uniq -c?","references":["https://www.gnu.org/software/coreutils/manual/coreutils.html","https://www.gnu.org/software/findutils/manual/find.pdf","https://www.gnu.org/software/grep/manual/grep.html"],"reviewAnswer":"Groups equal lines so adjacent counts are meaningful","reviewPrompt":"sort before uniq -c","sections":[{"body":"find selects filesystem entries; grep searches text. The quoted pattern *.go is passed to find rather than expanded by Bash. -exec passes each discovered filename as an argument, preserving spaces without parsing the output of ls.","code":"find . -type f -name \"*.go\"\nfind . -type f -name \"*.go\" -exec grep -nH -F \"ListenAndServe\" {} +","language":"bash","title":"Find source files and search their content","walkthrough":"The first command lists Go files. The second prints filename, line number and matching text. No matches can produce a nonzero grep status; distinguish that normal search outcome from an unreadable file."},{"body":"head shows the beginning, tail the end, and tail -f follows appended data until Ctrl-C. Bound a first inspection instead of loading a multi-gigabyte file. Filtering stdout does not capture stderr from a program unless you redirect it explicitly.","code":"head -n 10 app.log\ntail -n 40 app.log\ngrep -n -F \"timeout\" app.log\ntail -f app.log","language":"bash","title":"Read a bounded part of a log","walkthrough":"Stop tail -f with Ctrl-C when you have enough evidence. It does not stop the process writing the log. grep finds the literal timeout string and reports line numbers rather than interpreting it as a regular expression."},{"body":"uniq -c combines adjacent equal lines, so sort first if order does not matter. This simple pipeline counts exact repeated lines; real structured logs often contain a different timestamp per event and need field-aware parsing.","code":"grep -F \"ERROR\" app.log | sort | uniq -c | sort -nr | head -n 10","language":"bash","title":"Count repeated messages with a clear assumption","walkthrough":"The result is a frequency list of identical ERROR lines, not an error rate. With pipefail, an early writer can report a broken pipe when head exits; do not reuse a viewing pipeline as an unquestioned CI pass/fail gate."}],"takeaway":"Use find for paths and grep for text; quote patterns and preserve filenames as arguments. Bounded log inspection and explicit pipeline assumptions are more useful than printing every file.","title":"Find code and inspect logs from the command line","unitID":"operations","wrongAnswers":["uniq sorts every input line itself","sort changes error messages into exit codes"]},{"conceptTag":"tooling.bash","hint":"Count arguments after expansion, especially when a path contains spaces.","id":"operations.bash-arguments","introduction":"Bash is useful for connecting build and deployment tools on a developer machine. Go itself does not require Bash, Docker or Kubernetes. Learning their boundaries helps when a Go program becomes part of a service workflow; these commands are reading examples, not app terminal commands.","nuance":"Avoiding a shell prevents shell reinterpretation; the invoked tool still needs an allowed-operation contract.","objective":"Read a small build script without splitting paths or accidentally invoking a shell through Go.","question":"Which statement is correct about quoted bash array expansion?","references":["https://www.gnu.org/software/bash/manual/bash.html#Quoting","https://pkg.go.dev/os/exec"],"reviewAnswer":"Preserves each element as one command argument","reviewPrompt":"Quoted Bash array expansion","sections":[{"body":"Unquoted parameter expansion can perform word splitting and filename expansion. Quote a variable when its value should be one argument. In Bash, an array preserves several arguments without rebuilding a shell command string.","code":"#!/usr/bin/env bash\nset -u\nproject_dir=\"${1:-.}\"\nargs=(-C \"$project_dir\" test ./...)\ngo \"${args[@]}\"","language":"bash","title":"Preserve a path as one argument","walkthrough":"With a directory containing spaces, the array still supplies one directory argument. The script uses Bash-specific array syntax; it is not a portable /bin/sh script. The -C option changes Go's working directory before running the command."},{"body":"When a Go process starts a tool, exec.Command passes an argument vector directly. This avoids asking a shell to reinterpret semicolons, substitutions or spaces. It does not by itself make the target command safe; validate its allowed operation and arguments.","code":"cmd := exec.CommandContext(ctx, \"go\", \"test\", \"./...\")\ncmd.Dir = projectDir\ncmd.Stdout = os.Stdout\ncmd.Stderr = os.Stderr\nif err := cmd.Run(); err != nil {\n    return fmt.Errorf(\"go test: %w\", err)\n}","language":"go","title":"Keep data out of shell syntax","walkthrough":"This is native Go code for a development tool. It does not add subprocess execution to the iOS sandbox. Avoid sh -c with concatenated user input."},{"body":"A few fixed tool invocations can remain a script. Structured retries, complex state, concurrent work and testable domain rules often belong in Go. Quote \"$@\" when forwarding original arguments, avoid eval, and handle the exit status at the point where failure changes the workflow.","title":"Choose Go when the script stops being glue"}],"takeaway":"Preserve argument boundaries. Use Bash for small orchestration and direct process argument vectors from native Go when no shell language is needed.","title":"Bash passes arguments; quoting defines their boundaries","unitID":"operations","wrongAnswers":["It executes every argument as an independent shell script","It automatically authorizes any path passed by a user"]},{"conceptTag":"tooling.bash","hint":"Check which command supplies the pipeline's status before trusting its output.","id":"operations.bash-failures","introduction":"A script is another program with success and failure paths. A command printing plausible output can still fail. Pipelines complicate this because the last command can succeed even when an earlier producer failed.","nuance":"set -e has contextual exceptions; an explicit failure branch is often easier to reason about.","objective":"Read pipeline failure behavior and keep configuration and secrets out of command strings.","question":"Which statement is correct about bash pipefail?","references":["https://www.gnu.org/software/bash/manual/bash.html#Pipelines","https://www.gnu.org/software/bash/manual/bash.html#The-Set-Builtin"],"reviewAnswer":"Makes upstream failure affect the pipeline status","reviewPrompt":"Bash pipefail","sections":[{"body":"Bash pipefail makes a pipeline fail when a component fails, instead of using only the final command's status. Check that status explicitly at the workflow boundary. set -e has exceptions in conditionals and other constructs, so it is not a replacement for understanding control flow.","code":"#!/usr/bin/env bash\nset -u -o pipefail\nif go test ./... | tee test.log; then\n    printf \"%s\\n\" \"Tests passed\"\nelse\n    printf \"%s\\n\" \"Tests failed; inspect test.log\" >&2\n    exit 1\nfi","language":"bash","title":"Observe the whole pipeline","walkthrough":"tee preserves a log while showing output. With pipefail, a failing go test makes the condition fail even when tee succeeds. This script is for a trusted local project and writes one named log file."},{"body":"A prefix assignment belongs to one child process; export passes a variable to later children from this shell. Check selected non-secret settings instead of dumping the full environment. Already-running services keep their original environment.","code":"APP_ENV=development go run ./cmd/api\nexport APP_ENV=development\nprintf \"APP_ENV=%s\\n\" \"$APP_ENV\"\ncommand -v go","language":"bash","title":"Pass configuration and inspect one setting","walkthrough":"The first line runs a foreground API until you stop it; execute the following commands after it exits or in another shell. The example assumes cmd/api exists and does not require a credential. command -v shows which Go executable Bash will resolve."},{"body":"A trap can arrange cleanup of resources a script created, but it cannot roll back an external side effect automatically. Avoid rerunning a deployment simply because its status command timed out. Keep a stable operation identifier and inspect the outcome before retrying. As a script grows, move complex state transitions into a program with tests.","title":"Make cleanup and retries deliberate"}],"takeaway":"A successful last pipeline command does not prove upstream success. Preserve exit status, handle failure explicitly, and avoid exposing configuration secrets.","title":"Pipelines, exit codes and explicit failure handling","unitID":"operations","wrongAnswers":["tee reruns every failed Go test automatically","A pipeline always ignores the last command's status"]},{"conceptTag":"tooling.bash","hint":"Background work still has an outcome.","id":"operations.shell-processes","introduction":"A process has a PID, an exit status and open streams. Starting a service in the background does not detach it from responsibility: keep the PID and wait for completion. These commands assume a local Go project with cmd/api and an available port.","nuance":"A PID can be reused after exit; keep ownership instead of targeting processes by vague names.","objective":"Start one Go service, retain its PID, send TERM and wait for its result.","question":"What does wait \"$api_pid\" do for a child started in this shell?","references":["https://www.gnu.org/software/bash/manual/bash.html#Job-Control-Builtins","https://www.gnu.org/software/bash/manual/bash.html#Signals"],"reviewAnswer":"Observes completion and collects the child exit status","reviewPrompt":"Bash wait with a child PID","sections":[{"body":"Build first, then run the binary itself in the background. $! is the PID of the latest asynchronous command. A background go run process may introduce a build/launcher process, so it is a poor substitute when practicing exact signal ownership.","code":"mkdir -p bin\ngo build -o ./bin/api ./cmd/api\n./bin/api > api.log 2>&1 &\napi_pid=$!\nprintf \"API PID: %s\\n\" \"$api_pid\"","language":"bash","title":"Start the binary you can stop directly","walkthrough":"Run the launch only after the build succeeds. Both output streams go to api.log. Record this PID instead of searching all processes by a broad application name or terminating unrelated Go jobs."},{"body":"ps reports process state; kill -0 checks that a PID can be addressed without sending a signal. lsof is a separately installed utility on some systems and can identify a listening socket; it does not prove the HTTP handler returns useful responses.","code":"ps -p \"$api_pid\" -o pid,etime,args\nkill -0 \"$api_pid\"\nlsof -nP -iTCP:8080 -sTCP:LISTEN","language":"bash","title":"Inspect the process and the listening port","walkthrough":"Check that the socket belongs to the binary you launched. If lsof is missing, use your OS socket inspection tool. A process may exit between any two commands; observation is not a lifetime guarantee."},{"body":"TERM lets a cooperative service drain work. wait observes your shell child and reaps it; an if branch can preserve nonzero status without aborting the shell. SIGKILL prevents application cleanup, so use it only after diagnosing an unresponsive process.","code":"kill -TERM \"$api_pid\"\nif wait \"$api_pid\"; then\n    printf \"%s\\n\" \"Service exited successfully\"\nelse\n    status=$?\n    printf \"Service exit status: %s\\n\" \"$status\"\nfi\ntail -n 20 api.log","language":"bash","title":"Request shutdown and collect the outcome","walkthrough":"A graceful service can return zero. A process terminated by a signal may report a nonzero status; inspect its log and shutdown contract. wait works for children of this shell, not any arbitrary PID from another terminal."}],"takeaway":"Keep the child PID, inspect it, request TERM and wait for the outcome. A listening port, a live process and a successful HTTP response are three different observations.","title":"Processes, signals and exit status","unitID":"operations","wrongAnswers":["Kills every process named api","Retries the last failed network request"]},{"conceptTag":"tooling.bash","hint":"A child receives an environment when it starts.","id":"operations.shell-scripts","introduction":"A useful script has explicit inputs and predictable cleanup. Bash distinguishes positional arguments, shell variables and exported environment. This lesson puts those pieces into a small test wrapper instead of assuming that adding set -e makes every failure path correct.","nuance":"Configuration is not automatically secret; command traces and logs can reveal it.","objective":"Read required configuration, forward quoted arguments and clean a temporary workspace with a trap.","question":"What changes when you export APP_ENV?","references":["https://www.gnu.org/software/bash/manual/bash.html#Shell-Parameter-Expansion","https://www.gnu.org/software/bash/manual/bash.html#Bourne-Shell-Builtins"],"reviewAnswer":"Passes a variable to subsequently launched child processes","reviewPrompt":"export in Bash","sections":[{"body":"${1:-.} supplies a default when the first argument is absent or empty. A prefix assignment affects one command environment; export affects later child processes from this shell. Neither changes an already running service.","code":"project_dir=\"${1:-.}\"\nprintf \"Testing: %s\\n\" \"$project_dir\"\nGOMAXPROCS=2 go -C \"$project_dir\" test ./...\nexport APP_ENV=development\nprintf \"APP_ENV=%s\\n\" \"$APP_ENV\"","language":"bash","title":"Read arguments and pass a setting to one process","walkthrough":"The Go -C flag precedes the test command. The temporary GOMAXPROCS assignment does not permanently change your shell. Never print the complete environment to diagnose one non-secret setting."},{"body":"The : command with ${name:?message} reports a required input. mktemp creates the workspace, and EXIT runs cleanup on ordinary shell termination. The script forwards \"$@\" as separate arguments and uses an explicit test branch to preserve failure.","code":"#!/usr/bin/env bash\nset -u\n: \"${PROJECT_DIR:?Set PROJECT_DIR to a Go project}\"\nwork_dir=$(mktemp -d) || exit 1\ntrap 'rm -f \"$work_dir/test.log\"; rmdir \"$work_dir\"' EXIT\nif go -C \"$PROJECT_DIR\" test \"$@\" ./... > \"$work_dir/test.log\" 2>&1; then\n    cat \"$work_dir/test.log\"\nelse\n    cat \"$work_dir/test.log\" >&2\n    exit 1\nfi","language":"bash","title":"Validate inputs and clean only owned temporary data","walkthrough":"Save this as check.sh and call it with bash, PROJECT_DIR set, and optional go test flags such as -count=1. The trap names the one file it owns. SIGKILL and machine failure cannot run shell cleanup."},{"body":"bash -n parses without executing the script; it does not prove that command names, paths or remote systems exist. --help or command -v can establish what is installed. Review changes before making a script executable or putting it into CI.","code":"bash -n check.sh\ncommand -v bash\ncommand -v go\nPROJECT_DIR=\"$PWD\" bash check.sh -count=1","language":"bash","title":"Check syntax before running the script","walkthrough":"Syntax success is silent. The final line runs tests and can download required Go modules; it is an execution step, not another parser check. Keep credentials out of arguments and traces such as bash -x."}],"takeaway":"A script should declare its inputs, preserve argument boundaries and clean only resources it created. Parsing, executing and validating its external effects are separate checks.","title":"Small scripts: arguments, environment and cleanup","unitID":"operations","wrongAnswers":["Already running services receive the new value immediately","The value becomes a Kubernetes Secret"]},{"conceptTag":"tooling.git","hint":"The staging area is the next snapshot.","id":"operations.git-local","introduction":"Git records snapshots, not a magic backup of every unsaved editor buffer. Start in an existing local repository and inspect your changes. The sequence below makes a topic branch, stages one reviewed path and records a local commit; publishing comes in the next lesson.","nuance":"git restore --staged preserves the working file; plain git restore can replace it.","objective":"Keep working tree, staging area and committed history distinct.","question":"Which changes does git diff --staged show?","references":["https://git-scm.com/docs/git-status","https://git-scm.com/docs/git-diff","https://git-scm.com/docs/git-restore"],"reviewAnswer":"Shows the snapshot changes queued for the next commit","reviewPrompt":"git diff --staged","sections":[{"body":"git status --short summarizes tracked and untracked paths. git diff shows unstaged tracked changes; git diff --staged shows what the next commit contains. Untracked file content is not included in ordinary git diff.","code":"git status --short\ngit diff -- main.go\ngit diff --staged\ngit log -5 --oneline","language":"bash","title":"Inspect before selecting a change","walkthrough":"Compare the two diff views. A file can have both staged and unstaged edits, and the next commit includes only the staged snapshot. -- separates options/revisions from the path main.go."},{"body":"switch -c creates and selects a new branch at the current commit. add stages the named content. Inspect the staged result before committing, rather than using add . when a repository includes unrelated experiments or local credentials.","code":"git switch -c feature/health-check\ngit add -- main.go\ngit diff --staged\ngit commit -m \"Add health endpoint\"","language":"bash","title":"Put a reviewed change on a topic branch","walkthrough":"Use an unused branch name and a real main.go change. The commit remains local until you push it. If a hook fails, inspect its output and rerun the necessary check rather than bypassing it automatically."},{"body":"restore --staged changes the index back toward HEAD while leaving the working file intact. A plain restore of the working tree has a different, destructive meaning. Check both views after unstaging to make the distinction visible.","code":"git restore --staged -- main.go\ngit status --short\ngit diff -- main.go","language":"bash","title":"Unstage without discarding your edit","walkthrough":"Use this on a staged change before committing. Your edits should now be unstaged. This is not a command to undo an existing commit; history repair and reverting a published change are different operations."}],"takeaway":"Review unstaged and staged diffs separately, stage intended paths and commit on a named branch. Unstaging an edit preserves it; overwriting the working tree may discard it.","title":"Git daily work: inspect, branch, stage and commit","unitID":"operations","wrongAnswers":["Only untracked files not yet added","Every commit already pushed to every remote"]},{"conceptTag":"tooling.git","hint":"Fetch and integration are separate operations.","id":"operations.git-remotes","introduction":"A remote-tracking branch is your local record of a remote branch at the last fetch. Fetching updates that record without integrating it into your current branch. The examples assume an origin remote, a main branch and an existing topic branch you own.","nuance":"A rejected push should lead to comparison, not an automatic forced history rewrite.","objective":"Inspect upstream changes before integration and keep unfinished work recoverable.","question":"What does git fetch origin normally update?","references":["https://git-scm.com/docs/git-fetch","https://git-scm.com/docs/git-stash","https://git-scm.com/docs/git-pull","https://git-scm.com/docs/git-push"],"reviewAnswer":"Updates remote-tracking refs without merging into HEAD","reviewPrompt":"git fetch origin","sections":[{"body":"remote -v shows fetch and push destinations; inspect those before publishing. fetch origin updates remote-tracking references. The three-dot diff compares the topic branch against its merge base with origin/main, highlighting the branch contribution.","code":"git remote -v\ngit fetch origin\ngit log --oneline HEAD..origin/main\ngit diff origin/main...HEAD","language":"bash","title":"Fetch and compare before merging","walkthrough":"HEAD..origin/main lists commits reachable from origin/main but not HEAD. Fetch does not change your working files. A remote URL may contain sensitive information; avoid pasting it indiscriminately into public logs."},{"body":"stash push -u includes untracked files as well as tracked edits, but not ignored files by default. apply restores a stash while retaining its saved entry. Inspect and resolve any conflicts before deciding to drop the saved copy.","code":"git stash push -u -m \"WIP before syncing\"\ngit stash list\ngit stash show --stat \"stash@{0}\"\ngit stash apply \"stash@{0}\"\ngit status --short","language":"bash","title":"Temporarily store an unfinished tracked change","walkthrough":"Only apply when a stash entry actually exists. apply can conflict; it does not mean every file was restored cleanly. The retained stash is useful until the restored work is checked. A stash is local, not a shared backup."},{"body":"On a clean main branch, pull --ff-only refuses an implicit merge when histories diverge. A topic branch push sets its upstream without rewriting remote history. A rejected push is evidence to fetch and inspect, not a reason to force-push blindly.","code":"git switch main\ngit pull --ff-only origin main\ngit switch feature/health-check\ngit push -u origin feature/health-check","language":"bash","title":"Integrate deliberately and publish the branch","walkthrough":"Resolve or save local changes before switching branches. The pull updates main only if fast-forward is possible. Pushing the topic branch publishes commits; it does not merge them into main or submit an application release."}],"takeaway":"Fetch and compare before integrating. Preserve unfinished work, inspect conflicts and push the intended branch. Fast-forward refusal is a useful signal that history needs a deliberate decision.","title":"Git collaboration: fetch, compare, stash and push","unitID":"operations","wrongAnswers":["It merges origin/main into every local branch","It publishes all uncommitted files"]},{"conceptTag":"tooling.go-tools","hint":"Check the resulting dependency diff.","id":"operations.go-tooling","introduction":"A useful Go development loop checks the module boundary, formatting, tests, static diagnostics and the final build. These commands are for the native Go toolchain on a development machine; platform support and build tags can change which packages are selected.","nuance":"A race check covers executed paths and supported native targets, not every possible schedule.","objective":"Use the native Go CLI to inspect a module and check a service before packaging it.","question":"What should you do after go mod tidy?","references":["https://pkg.go.dev/cmd/go","https://go.dev/ref/mod","https://go.dev/doc/articles/race_detector"],"reviewAnswer":"Review the go.mod and go.sum changes before committing","reviewPrompt":"go mod tidy","sections":[{"body":"go version identifies the toolchain. go env GOMOD GOWORK prints selected module/workspace files without dumping every environment setting. list -m all describes the selected build list; mod why explains why a dependency is needed.","code":"go version\ngo env GOMOD GOWORK\ngo list -m all\ngo mod why -m golang.org/x/sync","language":"bash","title":"Locate the module and inspect dependencies","walkthrough":"Run inside your module; the selected module file should be the one you expect. The last dependency is an example: if it is not required, Go explains that. Module commands may access the configured proxy and network."},{"body":"gofmt -l lists formatting differences without rewriting files. test checks packages; -race adds supported native race instrumentation. vet reports suspicious constructs rather than proving semantic correctness. A clean run still depends on meaningful tests.","code":"gofmt -l .\ngo test ./...\ngo test -race ./...\ngo vet ./...","language":"bash","title":"Format, test and inspect suspicious code","walkthrough":"Run each check and inspect its status. Race detection needs a supported native platform/toolchain and may require cgo; it is not available through every cross-compilation target. A race-free test run covers only paths actually exercised."},{"body":"mod tidy can add or remove module requirements and sums, so review its diff rather than running it as an invisible deployment step. build -trimpath removes local filesystem paths from the executable; version -m inspects embedded build/module metadata.","code":"go mod tidy\ngit diff -- go.mod go.sum\nmkdir -p bin\ngo build -trimpath -o ./bin/api ./cmd/api\ngo version -m ./bin/api","language":"bash","title":"Tidy deliberately and inspect the shipped binary","walkthrough":"The example assumes cmd/api exists. Test any module file changes before committing. Embedded build metadata is useful for provenance, but build flags and source state must still be recorded for reproducible releases."}],"takeaway":"Check the selected module, format, test, race-check where supported, run vet and inspect the final artifact. Review dependency-file changes explicitly instead of treating tidy as a harmless read-only command.","title":"Go toolbelt: modules, tests, vet and build","unitID":"operations","wrongAnswers":["Assume it only prints dependency information","Delete go.sum because tidy makes it unnecessary"]},{"conceptTag":"tooling.networking","hint":"A transport success can still carry an HTTP error.","id":"operations.http-debugging","introduction":"An API can fail before any handler runs, or return an HTTP error over a perfectly healthy connection. curl helps identify that boundary. These examples target your own local Go service at 127.0.0.1:8080 with a /healthz endpoint; adjust the paths to your application.","nuance":"Do not assume curl exit status zero means the application returned HTTP 200.","objective":"Probe a local API and separate DNS, connection, HTTP and application failures.","question":"What does curl --fail-with-body add for HTTP 4xx or 5xx?","references":["https://curl.se/docs/manpage.html","https://pkg.go.dev/net/http"],"reviewAnswer":"Returns nonzero for HTTP errors and retains the body","reviewPrompt":"curl --fail-with-body","sections":[{"body":"-i includes response headers, --connect-timeout bounds connection establishment, and --max-time bounds the total operation. --fail-with-body makes HTTP 4xx/5xx nonzero while retaining the response body, unlike an ordinary successful curl transport.","code":"curl -i --connect-timeout 2 --max-time 5 \\\n  --fail-with-body http://127.0.0.1:8080/healthz","language":"bash","title":"Inspect headers and keep a timeout","walkthrough":"Expect a successful health response from your server. Connection refused means no reachable listener at that address, not an HTTP 500. A timeout has a different cause again; retain the specific diagnostic instead of reducing all failures to unavailable."},{"body":"--data-binary sends the provided bytes. The content type declares JSON, but the server still has to validate fields. This request is an example for a local /notes route accepting a text field; it is not an endpoint supplied by every Go service.","code":"curl -i --max-time 5 --fail-with-body \\\n  -H \"Content-Type: application/json\" \\\n  --data-binary '{\"text\":\"inspect this request\"}' \\\n  http://127.0.0.1:8080/notes","language":"bash","title":"Send JSON without hiding the request contract","walkthrough":"The single quotes keep Bash from interpreting the JSON double quotes. Data selects POST by default. Do not add a production authorization token to a shared example, shell history or a screenshot."},{"body":"--write-out prints transport timing after the request; -o /dev/null discards the body in this diagnostic. An HTTP status of 000 is not a server status: no HTTP response was received. Inspect hostname resolution separately when using a domain.","code":"curl -sS -o /dev/null --max-time 5 \\\n  -w 'status=%{http_code} connect=%{time_connect}s total=%{time_total}s\\n' \\\n  http://127.0.0.1:8080/healthz","language":"bash","title":"Measure and reason about the failed layer","walkthrough":"This timing command does not use --fail-with-body, so an HTTP 500 can still have curl status zero. Check both the printed HTTP status and the process outcome. Avoid -k as a default fix for TLS errors; correct the hostname and trust configuration."}],"takeaway":"Check transport errors, HTTP status and response body separately. Bound diagnostic requests and preserve the failed layer before deciding whether the problem is routing, TLS, a handler or a downstream dependency.","title":"HTTP debugging: curl, status codes and time budgets","unitID":"operations","wrongAnswers":["It retries every POST until it succeeds","It disables certificate verification"]},{"conceptTag":"tooling.linux","hint":"Unit configuration and process lifetime are separate.","id":"operations.linux-service","introduction":"A native Go binary can run directly under a service manager; Kubernetes is not required. These examples assume Linux with systemd and a preinstalled go-api.service. They do not apply to macOS launchd or every container environment.","nuance":"The service manager can report active while the application endpoint is failing.","objective":"Inspect a systemd service, follow its logs and understand its restart boundary.","question":"What does systemctl daemon-reload do?","references":["https://www.freedesktop.org/software/systemd/man/latest/systemctl.html","https://www.freedesktop.org/software/systemd/man/latest/journalctl.html"],"reviewAnswer":"Reloads unit definitions without restarting the service","reviewPrompt":"systemctl daemon-reload","sections":[{"body":"systemctl cat shows the installed unit and drop-ins. status includes active state and recent log context; show exposes selected properties. Verify the executable and service user before changing the process lifecycle.","code":"systemctl cat go-api.service\nsystemctl status go-api.service --no-pager\nsystemctl show go-api.service -p MainPID -p ActiveState -p SubState","language":"bash","title":"Read the unit and its current state","walkthrough":"An inactive or failed status can produce a nonzero exit code. Check ExecStart, WorkingDirectory and User in the unit. Unit content may reveal configuration paths; inspect only the required evidence before sharing logs."},{"body":"journalctl selects journal entries for a unit and time range. -f follows new entries; Ctrl-C stops following without stopping the service. Access may require membership or administrator permissions depending on the host configuration.","code":"journalctl -u go-api.service --since \"10 minutes ago\" --no-pager\njournalctl -u go-api.service -n 50 --no-pager\njournalctl -u go-api.service -f","language":"bash","title":"Follow the unit log instead of guessing a file path","walkthrough":"Correlate startup, request errors and shutdown timestamps. A missing journal permission is different from no application logs. The program should emit useful stdout/stderr records without credentials or full sensitive request payloads."},{"body":"daemon-reload reloads unit definitions after editing them; it does not restart a process by itself. restart replaces the running service and can interrupt traffic. An ordinary deployment needs a deliberate change window and an application shutdown budget.","code":"# After an intentional unit-file change on your own host:\nsudo systemctl daemon-reload\nsudo systemctl restart go-api.service\nsystemctl is-active go-api.service\ncurl --max-time 5 --fail-with-body http://127.0.0.1:8080/healthz","language":"bash","title":"Restart the intended service and verify recovery","walkthrough":"These two sudo commands mutate host state and need authorization on that machine. Verify both service state and HTTP behavior. A running process can still be unhealthy; repeated restarts can conceal a bad configuration instead of repairing it."}],"takeaway":"Inspect the unit, state and journal before restarting. Reloading definitions and replacing a process are distinct actions; verify the application endpoint after a controlled service change.","title":"A Go service on Linux: systemctl and journalctl","unitID":"operations","wrongAnswers":["It rotates all application passwords","It restarts every Go process immediately"]},{"conceptTag":"tooling.containers","hint":"List the runtime files before choosing scratch as a base image.","id":"operations.docker-build","introduction":"A container image packages a native application and its runtime files. It does not compile Go inside the iOS app, and it does not remove the need to maintain the operating environment. Multi-stage builds let the final image omit the compiler and source tree.","nuance":"A static executable may still need certificates, configuration, zoneinfo or writable storage.","objective":"Separate the build stage from the runtime image and identify what a minimal image leaves out.","question":"Which statement is correct about a multi-stage image build?","references":["https://docs.docker.com/build/building/multi-stage/","https://docs.docker.com/build/building/best-practices/"],"reviewAnswer":"Can omit the compiler from the runtime image","reviewPrompt":"A multi-stage image build","sections":[{"body":"The builder resolves dependencies and compiles a Linux binary. The final stage copies only the program. This example assumes go.mod and go.sum exist and the program lives in cmd/api.","code":"# syntax=docker/dockerfile:1\nFROM golang:1.27 AS build\nWORKDIR /src\nCOPY go.mod go.sum ./\nRUN go mod download\nCOPY . .\nRUN CGO_ENABLED=0 GOOS=linux go build -o /out/api ./cmd/api\n\nFROM scratch\nCOPY --from=build /out/api /api\nUSER 65532:65532\nEXPOSE 8080\nENTRYPOINT [\"/api\"]","language":"dockerfile","title":"Read the two stages","walkthrough":"This scratch example fits a compatible pure-Go binary with no required external files. It omits CA certificates, zoneinfo, a shell and writable application directories. Add the actual runtime assets or choose an appropriate maintained runtime base. Pin and update base image digests in a reproducible release process."},{"body":"Keep logs, local builds and secrets out of the build context with .dockerignore. Copy module files before source to reuse dependency work. The actual final image still needs a startup test; metadata inspection alone cannot prove its runtime files are sufficient.","code":"docker build -t go-api:dev .\ndocker image inspect go-api:dev --format '{{.Config.User}} {{json .Config.Entrypoint}}'\ndocker image ls go-api","language":"bash","title":"Build the final image and inspect its metadata","walkthrough":"For this Dockerfile the user should be 65532:65532 and the entrypoint /api. Verify the build succeeds before inspecting the tag, or you might inspect an older image. A CGO-dependent program needs a compatible build/runtime strategy."},{"body":"A non-root user reduces ordinary process privileges, but does not replace resource and filesystem limits. Test startup, configuration, TLS requirements and graceful termination using the actual final image. A compiler-stage unit test alone cannot prove the minimal runtime image contains the files the service needs.","title":"Run the artifact you intend to release"}],"takeaway":"Build with the toolchain, run with the required runtime files, and verify the final image. A smaller image must still satisfy the program's contract.","title":"Build a small Go image with explicit runtime needs","unitID":"containers","wrongAnswers":["It makes every Go dependency work without cgo","It guarantees scratch contains certificates and time-zone data"]},{"conceptTag":"tooling.containers","hint":"Image metadata is different from host networking.","id":"operations.docker-run","introduction":"Start with a trusted project containing the Dockerfile from the earlier lesson and a Go service listening on :8080. The following commands use an isolated development container named go-api-dev; an image, a container instance and a published port are different objects.","nuance":"The answer is no: publication requires an explicit runtime networking configuration.","objective":"Run a named local container and diagnose it with logs, inspect and stats.","question":"Does EXPOSE 8080 alone make a container port reachable on the host?","references":["https://docs.docker.com/reference/cli/docker/container/run/","https://docs.docker.com/reference/cli/docker/container/logs/","https://docs.docker.com/reference/cli/docker/container/stop/"],"reviewAnswer":"No; host publication needs a runtime port mapping","reviewPrompt":"Docker EXPOSE","sections":[{"body":"build tags the image produced from the current context. run creates a container; -d runs it in the background and -p publishes a container port at a host address. Bind the host side to loopback when the exercise should stay local.","code":"docker build -t go-api:dev .\ndocker run -d --name go-api-dev \\\n  -p 127.0.0.1:8080:8080 -e APP_ENV=development go-api:dev\ndocker ps --filter name=go-api-dev\ncurl --max-time 5 --fail-with-body http://127.0.0.1:8080/healthz","language":"bash","title":"Build once and start a named instance","walkthrough":"Run only after the build succeeds and choose another name or port if already used. The Go listener must accept container-interface traffic, usually :8080. EXPOSE in the Dockerfile alone does not publish anything on the host."},{"body":"logs reads stdout/stderr, inspect can select one property, and stats reports current resource usage. docker exec starts a new command inside the container; a scratch image has no sh, ls or other debugging utility unless you explicitly supplied one.","code":"docker logs --tail 50 go-api-dev\ndocker inspect --format '{{.State.Status}} {{.State.ExitCode}}' go-api-dev\ndocker stats --no-stream go-api-dev","language":"bash","title":"Inspect the instance and its actual runtime","walkthrough":"A stopped container is omitted by ordinary ps; use docker ps -a when investigating an exit. ExitCode is not an HTTP status. Avoid dumping all inspect properties when only state is needed because configuration can include sensitive environment data."},{"body":"stop sends a graceful termination signal and allows a finite timeout before forced termination. rm removes the stopped container, not the image or unrelated volumes. Replacing an image tag does not upgrade a previously created container.","code":"docker stop --timeout 15 go-api-dev\ndocker ps -a --filter name=go-api-dev\ndocker rm go-api-dev\ndocker image inspect go-api:dev --format '{{.Id}}'","language":"bash","title":"Stop and remove only this instance","walkthrough":"Confirm you no longer need the disposable instance before removing it. Persistent state belongs in deliberate storage; removing the container should not be your only backup strategy. Keep the image if you want to reproduce its startup."}],"takeaway":"Build an artifact, create a named instance and verify it through the published port. Inspect its own logs and exit state, then stop it deliberately; image tags and container instances have separate lifecycles.","title":"Docker daily commands: build, run, inspect and stop","unitID":"containers","wrongAnswers":["Yes, it always opens a public host listener","It only works if every process runs as root"]},{"conceptTag":"tooling.containers","hint":"Each container has its own loopback address.","id":"operations.docker-compose","introduction":"Compose defines a local multi-container environment in one file. This example assumes your API reads REDIS_ADDR, listens on :8080 and tolerates transient downstream failures. Use a disposable directory for the exercise and save the file below as compose.yaml.","nuance":"A startup health check is not a guarantee of future dependency availability.","objective":"Read compose.yaml and use config, up, ps, logs, exec and down.","question":"Where should this Compose API connect to Redis?","references":["https://docs.docker.com/compose/gettingstarted/","https://docs.docker.com/compose/how-tos/startup-order/","https://docs.docker.com/reference/cli/docker/compose/"],"reviewAnswer":"Lets api reach Redis at redis:6379 in this stack","reviewPrompt":"Compose service DNS","sections":[{"body":"Service names provide network discovery on the Compose network. The API connects to redis:6379, not its own localhost. A dependency health check orders initial startup; it does not guarantee Redis stays healthy, so the Go client still needs deadlines and recovery.","code":"services:\n  api:\n    build: .\n    ports: [\"127.0.0.1:8080:8080\"]\n    environment:\n      REDIS_ADDR: redis:6379\n    depends_on:\n      redis:\n        condition: service_healthy\n  redis:\n    image: redis:8-alpine\n    healthcheck:\n      test: [\"CMD\", \"redis-cli\", \"ping\"]\n      interval: 5s\n      timeout: 3s\n      retries: 5","language":"yaml","title":"Describe services and readiness in the file","walkthrough":"This intentionally disposable Redis has no persistent volume or public port. Choose a supported tested image version for your project and pin release digests when needed. The API Dockerfile must exist in the same build context."},{"body":"-p gives the stack a predictable project name. config --quiet validates without printing resolved configuration. up --build -d builds and starts; ps and logs reveal readiness and startup errors. Use the same project name for each command.","code":"docker compose -p go-lab config --quiet\ndocker compose -p go-lab up --build -d\ndocker compose -p go-lab ps\ndocker compose -p go-lab logs --tail 50 api redis","language":"bash","title":"Validate, start and inspect the project","walkthrough":"Configuration validation does not prove the images will build or the service will boot. A missing Dockerfile, unavailable image or failing Redis health check each needs its own fix. Avoid publishing the full resolved config if it includes secrets."},{"body":"exec runs inside an existing service container; redis-cli PING checks the Redis protocol path. down stops and removes the project containers and its normal networks. It does not delete named volumes unless requested with an additional destructive option.","code":"docker compose -p go-lab exec redis redis-cli PING\ncurl --max-time 5 --fail-with-body http://127.0.0.1:8080/healthz\ndocker compose -p go-lab down","language":"bash","title":"Probe a dependency and tear down deliberately","walkthrough":"PING should return PONG, while the HTTP check verifies your API route. Run down only when the local session is finished. This fixture uses ephemeral Redis storage, so its data goes away with the disposable container."}],"takeaway":"Use service DNS names inside a Compose network, validate the file and inspect each service. Initial dependency ordering complements application retry/deadline behavior; it does not replace it.","title":"Compose: run an API and Redis as one local stack","unitID":"containers","wrongAnswers":["127.0.0.1:6379 inside the API container","The Dockerfile EXPOSE instruction as a hostname"]},{"conceptTag":"tooling.containers","hint":"A volume has its own lifecycle.","id":"operations.docker-volumes","introduction":"A container writable layer usually disappears when its instance is removed. A bind mount maps a host path; a named volume has a lifecycle managed by the container runtime. These local examples use a dedicated fixture and Redis to demonstrate the difference.","nuance":"Surviving replacement does not protect a volume against host loss or deliberate deletion.","objective":"Choose a mount for configuration or persistent state and inspect it without deleting data.","question":"What normally happens to a named volume after docker rm without volume-removal flags?","references":["https://docs.docker.com/engine/storage/volumes/","https://docs.docker.com/engine/storage/bind-mounts/"],"reviewAnswer":"Can survive removal of the container using it","reviewPrompt":"A Docker named volume","sections":[{"body":"A bind mount exposes a host path to the container. --mount makes source, destination and read-only intent explicit. The example assumes ./config.json already exists and the API accepts a -config flag; adapt that flag to your own program.","code":"docker run --rm --name go-api-config \\\n  --mount \"type=bind,source=$PWD/config.json,target=/etc/go-api/config.json,readonly\" \\\n  go-api:dev -config /etc/go-api/config.json","language":"bash","title":"Mount a configuration file read-only","walkthrough":"Unlike some -v forms, --mount reports a missing source instead of silently making a directory. The image must let its configured user read the file. On macOS, file sharing also crosses the container VM boundary."},{"body":"Create a dedicated named volume and mount it at Redis data storage. Append-only persistence records writes into that volume; it does not create an off-host backup. The port remains private to this container unless you publish it separately.","code":"docker volume create go-lab-data\ndocker run -d --name go-lab-redis \\\n  --mount type=volume,source=go-lab-data,target=/data \\\n  redis:8-alpine redis-server --appendonly yes\ndocker exec go-lab-redis redis-cli SET example hello","language":"bash","title":"Give disposable Redis a separate data volume","walkthrough":"Use an unused container name. SET changes only this exercise Redis key. The volume survives removal of the container; persistence and restore procedures still need testing against the selected Redis version."},{"body":"Inspect mounts to confirm storage identity, then stop and remove only the Redis instance. The volume remains available for a later explicitly configured container. Avoid prune or rm -v as a casual repair for a service that owns important state.","code":"docker inspect --format '{{json .Mounts}}' go-lab-redis\ndocker stop go-lab-redis\ndocker rm go-lab-redis\ndocker volume inspect go-lab-data","language":"bash","title":"Remove an instance without deleting its stored data","walkthrough":"The final command should still find the named volume. A missing container is expected after rm. Delete the exercise volume later only when you intentionally no longer need its data and have checked its exact name."}],"takeaway":"Container replacement, volume deletion and backup are separate operations. Use explicit mount paths, account for the service UID and verify storage identity before changing the lifecycle of stateful workloads.","title":"Container storage: bind mounts, volumes and permissions","unitID":"containers","wrongAnswers":["It is always erased together with the image","It is automatically backed up to your Git remote"]},{"conceptTag":"tooling.containers","hint":"Identify whether an address belongs to the container, the VM or the host.","id":"operations.podman-runtime","introduction":"Docker and Podman can build and run OCI-style container images, but their host integration, daemon model, networking and rootless behavior are not identical. An image is an artifact; a container is a running or stopped instance with its own lifecycle.","nuance":"Rootless containers still need explicit resource, filesystem and network policies.","objective":"Distinguish image, container, host networking and persistent data while comparing local runtimes.","question":"Which statement is correct about container localhost?","references":["https://docs.podman.io/en/latest/markdown/podman.1.html","https://docs.podman.io/en/latest/markdown/podman-machine.1.html"],"reviewAnswer":"Refers to its network namespace, not the host","reviewPrompt":"Container localhost","sections":[{"body":"These Podman commands build an image from a trusted project and start one named container. The published port is restricted to the local host in this development example. Docker has similar basic commands, but do not assume every option and host behavior is interchangeable.","code":"podman build -t localhost/go-api:dev .\npodman run --rm --name go-api \\\n  -p 127.0.0.1:8080:8080 localhost/go-api:dev","language":"shell","title":"Read build and run separately","walkthrough":"The application inside the container must listen on an appropriate container interface, usually :8080, for port forwarding to reach it. Its own localhost is not the host's localhost. --rm removes this disposable container on exit; it does not manage external persistent data."},{"body":"Podman info reports the active environment; select only the rootless field when that is what you need. On macOS and Windows, Podman commonly uses a Linux VM. machine list and machine start manage that VM rather than the individual application container.","code":"podman info --format '{{.Host.Security.Rootless}}'\n# On macOS/Windows with an existing Podman machine:\npodman machine list\n# Start the chosen existing machine only if it is stopped:\npodman machine start","language":"bash","title":"Inspect rootless runtime and the container VM","walkthrough":"Linux installations may not use a Podman machine at all. Rootless does not mean unlimited host access or identical Docker networking. Inspect the selected connection and VM state before creating or restarting any shared environment."},{"body":"Run these in a second terminal while the earlier foreground go-api container is running. logs reads its stdout/stderr, ps selects its state and stop requests graceful termination. The earlier --rm option removes the disposable container on exit.","code":"podman ps --filter name=go-api\npodman logs --tail 50 go-api\npodman stats --no-stream go-api\npodman stop --time 15 go-api","language":"bash","title":"Inspect logs and stop the intended instance","walkthrough":"Use the exact exercise name so another service is not affected. Persistent data needs a deliberate volume and backup policy; --rm concerns the container instance, not an automatic external-storage lifecycle. The image remains available afterwards."}],"takeaway":"Images, instances, virtual-machine integration and persistent data are different layers. Similar command names do not establish identical runtime behavior.","title":"Docker and Podman: images are not running containers","unitID":"containers","wrongAnswers":["Every other container and the host at once","A public service endpoint automatically created by the runtime"]},{"conceptTag":"tooling.containers","hint":"Names and content identities are different.","id":"operations.container-registry","introduction":"A cluster pulls an image from a registry it can reach; a local Docker image does not appear there automatically. Tags are mutable names, while a digest identifies specific image content. Replace the example registry and owner with a namespace where you have permission to publish.","nuance":"A digest identifies content; platform compatibility and pull authorization still need verification.","objective":"Tag and push an image you own, inspect its digest and match its platform to the deployment.","question":"Why record a registry image digest for a release?","references":["https://docs.docker.com/reference/cli/docker/login/","https://docs.docker.com/reference/cli/docker/image/push/","https://docs.docker.com/build/building/multi-platform/"],"reviewAnswer":"Identifies image content more precisely than a mutable tag","reviewPrompt":"An image digest","sections":[{"body":"Use the registry credential flow appropriate to the host; --password-stdin keeps the token out of process arguments. This example reads a token interactively in Bash, passes it through stdin and unsets the variable after login.","code":"registry=registry.example.com\nread -r -s -p \"Registry token: \" registry_token\nprintf \"\\n\"\nprintf \"%s\" \"$registry_token\" | docker login \"$registry\" \\\n  --username YOUR_USER --password-stdin\nunset registry_token","language":"bash","title":"Authenticate without a password in the command line","walkthrough":"registry.example.com and YOUR_USER are placeholders. Do not run with shell tracing enabled or put tokens in a committed script. Docker stores credentials according to its configured credential helper; check that configuration on a shared host."},{"body":"Tagging gives the same local image another name; pushing uploads its referenced layers and manifest. Inspect the output digest and associate it with the source commit and tests. A tag called tested is still mutable unless the registry enforces otherwise.","code":"image=registry.example.com/YOUR_OWNER/go-api:0.1.0\ndocker tag go-api:dev \"$image\"\ndocker push \"$image\"\ndocker image inspect \"$image\" --format '{{json .RepoDigests}}'","language":"bash","title":"Publish an explicit version and record the result","walkthrough":"Replace owner and registry first and publish only your intended artifact. The digest from a successful push identifies the remote content. Referencing image@sha256:... in a deployment avoids relying on a mutable tag; use the full real digest, not an ellipsis."},{"body":"Buildx can build for a specified target when the builder supports it. A multi-platform image requires compatible toolchains, base images and code for each target. Setting GOOS alone does not ensure the native CPU architecture matches the Kubernetes node.","code":"docker buildx ls\ndocker buildx build --platform linux/amd64 \\\n  -t registry.example.com/YOUR_OWNER/go-api:0.1.0-amd64 --push .\ndocker buildx imagetools inspect registry.example.com/YOUR_OWNER/go-api:0.1.0-amd64","language":"bash","title":"Match the image platform to the target nodes","walkthrough":"This command publishes a separate amd64 tag. A compatible buildx builder may need emulation or native nodes. The earlier Dockerfile compiles inside its selected builder platform; custom cross-compilation needs explicit GOARCH/TARGETARCH handling."}],"takeaway":"Publish to an owned registry namespace, retain the pushed digest and verify the target platform. A local tag or a successful host build does not prove a cluster can pull and run that artifact.","title":"Publish an image: tags, digests and target platforms","unitID":"containers","wrongAnswers":["A tag can never be updated once pushed","A digest provides database backups automatically"]},{"conceptTag":"tooling.kubernetes","hint":"A context includes the cluster and user identity.","id":"operations.kubernetes-contexts","introduction":"kubectl reads a kubeconfig and sends requests to its selected cluster as a configured identity. A namespace narrows many workload operations but does not select a cluster. These lessons assume an existing disposable development cluster with a context named dev-cluster; substitute your actual development context.","nuance":"Authorization and reachability are separate checks; a context name alone is not proof of the intended server.","objective":"Inspect the target cluster and explicitly scope commands before making changes.","question":"What does kubectl --context select for one invocation?","references":["https://kubernetes.io/docs/concepts/configuration/organize-cluster-access-kubeconfig/","https://kubernetes.io/docs/concepts/overview/working-with-objects/namespaces/","https://kubernetes.io/docs/reference/kubectl/quick-reference/"],"reviewAnswer":"Selects the kubeconfig context for one invocation","reviewPrompt":"kubectl --context","sections":[{"body":"config get-contexts lists saved contexts, and current-context prints the default. A context bundles cluster, identity and an optional namespace. These commands inspect local configuration; they do not establish whether the remote API is reachable.","code":"kubectl config get-contexts\nkubectl config current-context\nkubectl --context dev-cluster cluster-info","language":"bash","title":"Identify the context before querying workloads","walkthrough":"Replace dev-cluster with the development context you inspected. Avoid config view --raw in shared output because it can reveal credentials. Supplying --context on later commands avoids silently targeting a different default cluster."},{"body":"get namespaces shows available namespaces when your identity is allowed to list them. api-resources tells you the kinds the server exposes. auth can-i checks authorization for one requested action; it is not a proof that the action will otherwise succeed.","code":"kubectl --context dev-cluster get namespaces\nkubectl --context dev-cluster api-resources --namespaced=true\nkubectl --context dev-cluster auth can-i create deployments -n go-lab","language":"bash","title":"Find namespaces and discover resource types","walkthrough":"A no response from can-i means your identity lacks that permission. An absent go-lab namespace must be created deliberately by an authorized user before the later exercises. Do not switch to a more privileged production credential as an automatic workaround."},{"body":"Create go-lab only on the inspected development cluster if it does not exist. -n selects the namespace for the request. Pod queries can be watched with -w; Ctrl-C stops watching without deleting any workload.","code":"# One-time setup if go-lab does not exist:\nkubectl --context dev-cluster create namespace go-lab\nkubectl --context dev-cluster -n go-lab get pods -o wide\nkubectl --context dev-cluster -n go-lab get pods -w","language":"bash","title":"Scope a development namespace explicitly","walkthrough":"An empty namespace correctly reports no resources. AlreadyExists from create means the setup already happened; inspect before reusing a namespace someone else owns. Namespace deletion later would delete its namespaced resources, so it is not a casual cleanup command."}],"takeaway":"Know the context, identity and namespace before working on a cluster. Keep the development context and namespace explicit in commands; a namespace flag alone cannot protect against targeting the wrong cluster.","title":"kubectl first steps: context, namespace and permissions","unitID":"kubernetes","wrongAnswers":["--namespace changes both the cluster and identity","--all-namespaces grants administrator privileges"]},{"conceptTag":"tooling.kubernetes","hint":"Trace Deployment selector, Pod label and Service selector together.","id":"operations.kubernetes-workloads","introduction":"Kubernetes operates containerized workloads. It does not write your Go code or remove distributed-system failures. A Deployment describes the desired replicated workload; a Service gives selected Pods a stable network abstraction while individual Pods are replaced.","nuance":"Scaling replicas also scales their downstream connection pools and worker pressure.","objective":"Read Deployment, Pod labels, resource budgets and a Service without confusing them with an application build.","question":"Which statement is correct about a kubernetes service selector?","references":["https://kubernetes.io/docs/concepts/workloads/controllers/deployment/","https://kubernetes.io/docs/concepts/services-networking/service/","https://kubernetes.io/docs/concepts/configuration/manage-resources-containers/"],"reviewAnswer":"Chooses matching Pod labels for stable routing","reviewPrompt":"A Kubernetes Service selector","sections":[{"body":"This abbreviated manifest connects a Service to Pods carrying app: go-api. The image reference is a placeholder for an image you have built, tested and published to an accessible registry. Read it as configuration, not something the iOS app can apply.","code":"apiVersion: apps/v1\nkind: Deployment\nmetadata:\n  name: go-api\nspec:\n  replicas: 2\n  selector:\n    matchLabels: {app: go-api}\n  template:\n    metadata:\n      labels: {app: go-api}\n    spec:\n      containers:\n        - name: api\n          image: your-registry/go-api:tested\n          ports: [{containerPort: 8080}]\n          resources:\n            requests: {cpu: \"100m\", memory: \"128Mi\"}\n            limits: {cpu: \"1\", memory: \"512Mi\"}\n---\napiVersion: v1\nkind: Service\nmetadata:\n  name: go-api\nspec:\n  selector: {app: go-api}\n  ports: [{port: 80, targetPort: 8080}]","language":"yaml","title":"Follow selectors and labels","walkthrough":"The numbers illustrate syntax, not capacity recommendations. This Service is internal by default; public ingress, TLS and authentication need their own design. The Deployment example still needs suitable probe and shutdown policies."},{"body":"Requests influence scheduling; CPU and memory limits have different runtime effects. Use the Pod specification and Deployment state to inspect the declared budget, then compare with metrics if the cluster exposes them. The sample numbers are illustrative rather than recommendations.","code":"kubectl --context dev-cluster -n go-lab get deployment go-api\nkubectl --context dev-cluster -n go-lab get pods -l app=go-api -o wide\nkubectl --context dev-cluster -n go-lab get deployment go-api \\\n  -o jsonpath='{.spec.template.spec.containers[0].resources}{\"\\n\"}'","language":"bash","title":"Observe replicas, requests and limits","walkthrough":"Run after the context/setup and apply lessons. Two replicas each allowing fifty downstream calls can present a hundred simultaneous calls. Resource declarations do not measure actual usage; memory exhaustion can terminate a container while CPU limits can throttle it."},{"body":"Rolling replacement and service discovery help teams operating many workloads, but cluster maintenance and debugging cost time. A VM, a managed service or a single container host can be simpler for a small application. Learn the reconciliation model before copying a large production manifest, and inspect a plan in a non-production environment before applying it.","title":"Use orchestration only when it pays for itself"}],"takeaway":"Match labels to selectors, give each replica a resource and downstream budget, and treat public routing as a separate concern.","title":"Kubernetes reconciles a workload; a Service routes to it","unitID":"kubernetes","wrongAnswers":["By reading the package name of the Go executable","By compiling every image named in the cluster"]},{"conceptTag":"tooling.kubernetes","hint":"A visible difference is an intended diff outcome.","id":"operations.kubernetes-apply","introduction":"A manifest declares desired state; the API accepting it is only the start of reconciliation. Save the earlier Deployment and Service example as deployment.yaml, set a real pullable image reference and use the go-lab development namespace from the context lesson.","nuance":"Dry-run validates a request but does not test image availability or scheduling.","objective":"Validate a workload document and observe reconciliation rather than assuming apply means ready.","question":"What does kubectl diff returning exit status 1 normally mean?","references":["https://kubernetes.io/docs/reference/kubectl/generated/kubectl_apply/","https://kubernetes.io/docs/reference/kubectl/generated/kubectl_diff/","https://kubernetes.io/docs/reference/kubectl/generated/kubectl_explain/"],"reviewAnswer":"Means live state differs from the proposed manifest","reviewPrompt":"kubectl diff exit status 1","sections":[{"body":"explain documents a field from the API schema. apply --dry-run=server asks the server to validate and default the request without persisting it. It still requires API access and appropriate permission and can depend on admission configuration.","code":"kubectl --context dev-cluster explain deployment.spec.template.spec.containers\nkubectl --context dev-cluster -n go-lab apply \\\n  --dry-run=server -f deployment.yaml","language":"bash","title":"Read the schema and validate with the server","walkthrough":"Fix unknown fields and validation errors before the real apply. A successful dry run does not schedule Pods, pull images or test your application. Only submit trusted reviewed files, including any resource namespace declared inside them."},{"body":"diff compares the proposed object with live state; exit one means differences, not necessarily a failed comparison. apply persists the desired resource changes, so inspect the exact files and target namespace before this mutation.","code":"kubectl --context dev-cluster -n go-lab diff -f deployment.yaml\nkubectl --context dev-cluster -n go-lab apply -f deployment.yaml","language":"bash","title":"Review the delta and apply the intended state","walkthrough":"kubectl diff uses status zero for no changes, one for differences and greater than one for errors. Do not hide all nonzero codes with || true in automation. apply may create or update several documents from this file."},{"body":"rollout status waits for a Deployment update to finish within a timeout. get reports objects and their current state; it does not prove every business request succeeds. A timeout should lead to diagnosis of the existing rollout before another deployment attempt.","code":"kubectl --context dev-cluster -n go-lab rollout status deploy/go-api --timeout=120s\nkubectl --context dev-cluster -n go-lab get deploy,rs,pods,svc -l app=go-api\nkubectl --context dev-cluster -n go-lab get svc go-api","language":"bash","title":"Wait for convergence and inspect the resulting objects","walkthrough":"The original Service example does not give the Service object an app label, so the final explicit Service query is necessary. Inspect readiness, image pulls and events if convergence fails. A successful apply alone is not release success."}],"takeaway":"Validate a reviewed document, understand diff exit codes, apply once and observe the rollout. API acceptance and a ready, functional application are separate milestones.","title":"Deploy a manifest: explain, dry-run, diff and apply","unitID":"kubernetes","wrongAnswers":["The manifest was successfully deployed","The cluster has exactly one failed Pod"]},{"conceptTag":"tooling.kubernetes","hint":"A restarted container has a previous instance.","id":"operations.kubernetes-inspect","introduction":"Read the workload state before changing it. A Deployment, a Pod and a container can each have a different status, so diagnose the layer that is failing. These commands refer to the earlier go-api Deployment in the explicit go-lab development namespace.","nuance":"Container logs and events have retention limits; use centralized collection for durable history.","objective":"Find the concrete reason behind Pending, CrashLoopBackOff or an unready container.","question":"Which logs can --previous retrieve for a restarted container?","references":["https://kubernetes.io/docs/tasks/debug/debug-application/debug-pods/","https://kubernetes.io/docs/reference/kubectl/generated/kubectl_logs/","https://kubernetes.io/docs/tasks/debug/debug-application/debug-running-pod/"],"reviewAnswer":"Reads logs from the previous terminated container instance","reviewPrompt":"kubectl logs --previous","sections":[{"body":"get -o wide includes node and Pod addresses. describe exposes scheduling decisions, container state and recent events. Copy the exact Pod name from get rather than inventing an identifier; the placeholder below must be replaced.","code":"kubectl --context dev-cluster -n go-lab get pods -l app=go-api -o wide\npod_name=REPLACE_WITH_ACTUAL_POD\nkubectl --context dev-cluster -n go-lab describe pod \"$pod_name\"\nkubectl --context dev-cluster -n go-lab get events --sort-by=.metadata.creationTimestamp","language":"bash","title":"Find the Pod and read its events","walkthrough":"Pending often needs scheduling/volume evidence; ImagePullBackOff needs the image or registry failure. CrashLoopBackOff describes retry backoff after container failure, not a root cause. Check the reported reason and exit code first."},{"body":"logs reads application stdout/stderr. -c selects the container name api from the earlier manifest. --previous requests the last terminated instance when one exists, which is valuable when the current container restarted before you could follow it.","code":"kubectl --context dev-cluster -n go-lab logs \"$pod_name\" -c api --tail=100\nkubectl --context dev-cluster -n go-lab logs \"$pod_name\" -c api --previous --tail=100\nkubectl --context dev-cluster -n go-lab logs \"$pod_name\" -c api -f --since=5m","language":"bash","title":"Read the right container and the previous attempt","walkthrough":"No previous container is a valid reason for --previous to fail. Ctrl-C only stops following logs. Redact sensitive application data before sharing output and correlate timestamps with restarts and rollout events."},{"body":"top requires the cluster metrics API, commonly provided by Metrics Server. exec starts a command that already exists in the image; the earlier scratch Go image has no shell. For richer diagnosis, use an approved ephemeral debug image and the required cluster permissions.","code":"kubectl --context dev-cluster -n go-lab top pods -l app=go-api\nkubectl --context dev-cluster top nodes\n# Only for an image that actually contains /bin/sh:\nkubectl --context dev-cluster -n go-lab exec -it \"$pod_name\" -c api -- /bin/sh","language":"bash","title":"Inspect resources and choose an available debug path","walkthrough":"A missing metrics API does not mean resource usage is zero. The exec line will fail for scratch images by design; use logs, profiles or a deliberate debug-container workflow instead of assuming every production image includes utilities."}],"takeaway":"Read exact state, events, container logs and resource evidence before restarting. Previous logs can explain a crash loop; missing metrics or a missing shell is a tooling boundary, not an application diagnosis.","title":"Debug Pods: get, describe, logs, events and top","unitID":"kubernetes","wrongAnswers":["All logs from every deleted Pod forever","Only HTTP requests from the host browser"]},{"conceptTag":"tooling.kubernetes","hint":"The local forwarding process has a lifetime.","id":"operations.kubernetes-network","introduction":"A Service object can exist while routing to no useful Pods. Diagnose its selector, selected endpoints, target port and application listener separately. This lesson uses the earlier internal Service go-api on port 80 targeting the Go container port 8080.","nuance":"A tunnel request can succeed while the normal network-policy path still fails.","objective":"Trace a request from a local port through a Service to a ready application endpoint.","question":"What does port-forward create in this development example?","references":["https://kubernetes.io/docs/concepts/services-networking/service/","https://kubernetes.io/docs/tasks/access-application-cluster/port-forward-access-application-cluster/","https://kubernetes.io/docs/concepts/services-networking/dns-pod-service/"],"reviewAnswer":"Creates a temporary local tunnel, not public ingress","reviewPrompt":"kubectl port-forward","sections":[{"body":"A Service selector matches Pod labels; EndpointSlices describe backend addresses and readiness. Deployment existence alone does not prove the Service selected its Pods. Query the named Service because the sample object does not have an app metadata label.","code":"kubectl --context dev-cluster -n go-lab describe service go-api\nkubectl --context dev-cluster -n go-lab get pods -l app=go-api --show-labels\nkubectl --context dev-cluster -n go-lab get endpointslices \\\n  -l kubernetes.io/service-name=go-api -o wide","language":"bash","title":"Check selector and ready endpoints","walkthrough":"Empty endpoints suggest a selector mismatch, missing Pods or readiness problems. Compare targetPort 8080 with the actual Go listener. A listener bound to 127.0.0.1 inside the Pod cannot normally serve traffic arriving at its Pod interface."},{"body":"port-forward supplies a temporary local development path; it is not a public ingress or load test. Bind it to loopback and keep the process running while you use a second terminal to call the local address.","code":"# Terminal 1; stop with Ctrl-C:\nkubectl --context dev-cluster -n go-lab port-forward \\\n  --address 127.0.0.1 service/go-api 8080:80\n# Terminal 2:\ncurl --max-time 5 --fail-with-body http://127.0.0.1:8080/healthz","language":"bash","title":"Forward one local port and make a bounded request","walkthrough":"The local 8080 forwards to Service port 80, which resolves to a Pod target. If another local process owns 8080, choose a different local port. The session can end when its selected Pod disappears; it does not create durable routing."},{"body":"An in-cluster client in go-lab can normally resolve go-api; a client in another namespace can use go-api.go-lab.svc.cluster.local on a cluster using that DNS suffix. Network policy and DNS configuration still apply. A port-forward does not prove the ordinary in-cluster network route works.","code":"kubectl --context dev-cluster -n go-lab get service go-api -o yaml\nkubectl --context dev-cluster -n go-lab get networkpolicy","language":"bash","title":"Distinguish application access from a diagnostic tunnel","walkthrough":"Check Service type, ports and selectors in the first output. No policies in this namespace is not a complete security audit: cluster networking and other policy mechanisms can also affect traffic. Ingress, public TLS and authentication need their own configuration."}],"takeaway":"Trace labels, endpoint readiness, Service ports and the listener as separate links. Port-forward is a useful temporary tunnel, but it cannot validate all normal service-network and public-ingress behavior.","title":"Service routing: selectors, endpoints and port-forward","unitID":"kubernetes","wrongAnswers":["A permanent load balancer for all internet clients","A new container image with DNS installed"]},{"conceptTag":"tooling.kubernetes","hint":"A running process keeps its environment.","id":"operations.kubernetes-config","introduction":"Separate application configuration from the image artifact. ConfigMaps hold ordinary configuration; Secrets are intended for sensitive values but are not made confidential merely by base64 encoding. These development examples assume a namespace you own and the permissions to manage its configuration.","nuance":"Base64 is an encoding, not encryption or an access-control policy.","objective":"Create a non-secret setting, mount a Secret reference and understand why environment changes need replacement.","question":"When does a process receive a ConfigMap-backed environment variable?","references":["https://kubernetes.io/docs/concepts/configuration/configmap/","https://kubernetes.io/docs/concepts/configuration/secret/","https://kubernetes.io/docs/tasks/configure-pod-container/configure-pod-configmap/"],"reviewAnswer":"Is captured when the container process starts","reviewPrompt":"ConfigMap-backed environment","sections":[{"body":"create with --dry-run=client -o yaml generates an object locally. Piping that object to apply creates or updates the named configuration on the explicit cluster. LOG_LEVEL is an ordinary non-secret value here, so showing its key is appropriate.","code":"kubectl --context dev-cluster -n go-lab create configmap go-api-config \\\n  --from-literal=LOG_LEVEL=info --dry-run=client -o yaml | \\\n  kubectl --context dev-cluster -n go-lab apply -f -\nkubectl --context dev-cluster -n go-lab describe configmap go-api-config","language":"bash","title":"Generate and apply a non-secret ConfigMap","walkthrough":"In a Bash script, enable pipefail and handle the pipeline status. The first command only generates YAML; the second performs the API mutation. Do not use a ConfigMap for a database password or access token."},{"body":"This is a fragment to merge into the api container in deployment.yaml, not a standalone manifest. It assumes an existing go-api-credentials Secret with a password key, supplied through your cluster secret-management process.","code":"env:\n  - name: LOG_LEVEL\n    valueFrom:\n      configMapKeyRef:\n        name: go-api-config\n        key: LOG_LEVEL\n  - name: DB_PASSWORD\n    valueFrom:\n      secretKeyRef:\n        name: go-api-credentials\n        key: password","language":"yaml","title":"Reference existing config and secret keys from the Pod","walkthrough":"The application reads these values when its process starts. Restrict Secret access and configure storage protection at the cluster level. Never commit live Secret YAML or paste decoded credentials into a lesson exercise."},{"body":"Changing the ConfigMap does not rewrite environment variables in a running process. A controlled rollout restart replaces Pods so they read the updated values. ConfigMap volume updates have different propagation and application-reload behavior, and subPath mounts do not receive normal automatic updates.","code":"kubectl --context dev-cluster -n go-lab rollout restart deployment/go-api\nkubectl --context dev-cluster -n go-lab rollout status deployment/go-api --timeout=120s\nkubectl --context dev-cluster -n go-lab get pods -l app=go-api","language":"bash","title":"Replace Pods when environment configuration changes","walkthrough":"Only restart after the reviewed configuration and Pod template are ready. Observe readiness and service behavior afterwards without logging the password. This restart changes running workloads; it is not a read-only configuration check."}],"takeaway":"Use ConfigMaps for ordinary values and controlled Secret references for credentials. Environment is captured at process startup; replacing Pods and reloading mounted files are distinct update strategies.","title":"Configuration: ConfigMaps, Secrets and update behavior","unitID":"kubernetes","wrongAnswers":["Every time kubectl get pods is called","Immediately whenever any Secret in the cluster changes"]},{"conceptTag":"tooling.kubernetes","hint":"For each health failure, name the action the platform should take.","id":"operations.probes-and-shutdown","introduction":"A process being alive does not mean it can accept useful work. Readiness controls whether a Pod receives normal Service traffic. Liveness can trigger a restart. A startup probe can allow initialization before the other probes take effect. Choose each signal according to the failure it should detect.","nuance":"Use a fresh bounded drain context; the signal context is already canceled when shutdown starts.","objective":"Give each health signal one purpose and arrange a bounded stop that drains owned work.","question":"Which statement is correct about readiness and liveness?","references":["https://kubernetes.io/docs/concepts/workloads/pods/probes/","https://pkg.go.dev/net/http#Server.Shutdown","https://kubernetes.io/docs/concepts/workloads/pods/pod-lifecycle/"],"reviewAnswer":"Readiness gates traffic; liveness can trigger a restart","reviewPrompt":"Readiness and liveness","sections":[{"body":"Merge this fragment into the api container only if the Go server implements these endpoints. Readiness gates normal Service traffic; liveness should detect a condition a restart can repair. A startup probe delays the other probes until startup succeeds.","code":"startupProbe:\n  httpGet: {path: /healthz, port: 8080}\n  periodSeconds: 2\n  failureThreshold: 30\nreadinessProbe:\n  httpGet: {path: /readyz, port: 8080}\n  periodSeconds: 5\nlivenessProbe:\n  httpGet: {path: /healthz, port: 8080}\n  periodSeconds: 10","language":"yaml","title":"Give each probe one action","walkthrough":"The intervals are examples, not universal budgets. A shared Redis outage should not make every liveness endpoint fail and restart all replicas. Readiness should reflect the service degraded-mode contract; test the actual handler behavior."},{"body":"This native Go fragment assumes srv is already serving in another goroutine. The signal context requests shutdown; a separate context bounds draining so an already-canceled signal context does not abort it immediately.","code":"stopCtx, stop := signal.NotifyContext(context.Background(),\n    os.Interrupt, syscall.SIGTERM)\ndefer stop()\n<-stopCtx.Done()\n\ndrainCtx, cancel := context.WithTimeout(context.Background(), 10*time.Second)\ndefer cancel()\nif err := srv.Shutdown(drainCtx); err != nil {\n    return fmt.Errorf(\"drain HTTP: %w\", err)\n}","language":"go","title":"Drain requests within a finite deadline","walkthrough":"Ten seconds is illustrative and must fit the platform termination grace period. Shutdown does not automatically wait for every background worker or hijacked connection. Stop accepting work, signal owned workers, join them, and close shared clients in a deliberate order."},{"body":"Readiness changes and endpoint propagation take time; applications can still see late requests. Make handlers safe during draining, choose how to reject new work, and verify existing requests finish or fail predictably. Persist required background work before exit. Probe intervals and thresholds should fit startup and recovery behavior instead of creating a rapid restart loop.","title":"Test the termination path under traffic"}],"takeaway":"A health check needs an action model: route traffic, wait for startup, or restart. Graceful shutdown requires explicit ownership, deadlines and a tested drain path.","title":"Readiness, liveness and graceful shutdown","unitID":"kubernetes","wrongAnswers":["Liveness, because every dependency failure must restart the Pod","A CPU profile taken once when the image was built"]},{"conceptTag":"tooling.kubernetes","hint":"A Deployment revision tracks its workload template.","id":"operations.kubernetes-rollout","introduction":"A Deployment rollout changes its Pod template and replaces replicas under its update policy. A timeout or unhealthy Pod requires investigation before further mutations. These examples operate only on the inspected development go-api Deployment, using a real tested image reference in place of the placeholder.","nuance":"History retention and backward-compatible data changes determine whether rollback can succeed.","objective":"Change an image deliberately, observe revisions and understand what rollback cannot restore.","question":"What can Deployment rollout undo restore?","references":["https://kubernetes.io/docs/concepts/workloads/controllers/deployment/","https://kubernetes.io/docs/reference/kubectl/generated/kubectl_rollout/","https://kubernetes.io/docs/reference/kubectl/generated/kubectl_scale/"],"reviewAnswer":"Restores a retained previous Pod template revision","reviewPrompt":"Deployment rollout undo","sections":[{"body":"rollout history lists retained Deployment revisions. set image changes the api container image in the Pod template. Use an immutable image digest in a real release where reproducibility matters, and keep the declarative source in sync with this operational change.","code":"kubectl --context dev-cluster -n go-lab rollout history deployment/go-api\nkubectl --context dev-cluster -n go-lab set image deployment/go-api \\\n  api=registry.example.com/YOUR_OWNER/go-api:0.1.1\nkubectl --context dev-cluster -n go-lab rollout status deployment/go-api --timeout=120s","language":"bash","title":"Inspect history and set the intended artifact","walkthrough":"Replace the registry, owner and version with a published tested artifact before running. set image mutates the cluster immediately. A future apply from an old manifest can overwrite the change; version-controlled deployment configuration should describe the intended final state."},{"body":"scale changes desired replicas, not the size of an individual process. Check workload state and pressure afterwards. Requests, limits, database pools and worker concurrency multiply across replicas; an autoscaler or another controller may subsequently change the count.","code":"kubectl --context dev-cluster -n go-lab scale deployment/go-api --replicas=3\nkubectl --context dev-cluster -n go-lab get deployment go-api\nkubectl --context dev-cluster -n go-lab get pods -l app=go-api\nkubectl --context dev-cluster -n go-lab top pods -l app=go-api","language":"bash","title":"Scale with resource and downstream budgets in mind","walkthrough":"Three replicas are a syntax example, not a capacity recommendation. top requires a metrics API. Confirm the cluster can schedule the workload and downstream systems can handle its multiplied demand rather than treating replica count as free capacity."},{"body":"undo uses a retained earlier Deployment revision. It can restore the Pod template, but cannot reverse a database migration, external side effect or independently changed Secret/ConfigMap. Inspect the selected history revision and its artifact before a deliberate rollback.","code":"kubectl --context dev-cluster -n go-lab rollout history deployment/go-api\n# After selecting and reviewing an appropriate previous revision:\nkubectl --context dev-cluster -n go-lab rollout undo deployment/go-api\nkubectl --context dev-cluster -n go-lab rollout status deployment/go-api --timeout=120s","language":"bash","title":"Roll back a Pod template, then verify the service","walkthrough":"The undo line chooses the previous retained revision; use --to-revision with an inspected real number for an explicit choice. Afterwards verify readiness, logs and the API through a fresh test request. Do not repeatedly undo merely because a status command timed out."}],"takeaway":"Record the released image, observe the rollout and budget replicas against downstream capacity. Rollback restores a retained workload template, not databases or every separate configuration object.","title":"Release operations: rollout, scale and rollback","unitID":"kubernetes","wrongAnswers":["Every database write made by the new version","All deleted Secrets and persistent-volume backups"]},{"conceptTag":"devops.delivery-loop","designGuide":{"cautions":["A useful automation reduces repeated manual work while keeping changes bounded, observable and recoverable; its command count is not the success criterion."],"cost":"Automation needs explicit ownership, bounded privileges, tests and recovery evidence; a shorter command is not sufficient.","family":"Go for DevOps and reliability","flow":["Define a small contract","Verify one artifact","Observe the deployed result","Feed evidence back"],"ratings":[],"strengths":["Connect a service change to tests, delivery, operation and feedback, and choose a small automation project with a measurable outcome.","Make changes reviewable and verify the result against the original contract."]},"hint":"Measure a repeatable outcome and retain failure/recovery evidence.","id":"devops.delivery-loop","introduction":"A DevOps engineer helps teams deliver and operate changes reliably. Go is useful for portable command-line tools, controllers, exporters and services. The work also involves Linux, networking, release ownership, incident response and collaboration. Start with one service and a repeatable feedback loop rather than collecting tool names.","nuance":"A useful automation reduces repeated manual work while keeping changes bounded, observable and recoverable; its command count is not the success criterion.","objective":"Connect a service change to tests, delivery, operation and feedback, and choose a small automation project with a measurable outcome.","question":"Which sequence forms a DevOps delivery feedback loop?","references":["https://go.dev/solutions/devops","https://sre.google/sre-book/eliminating-toil/","https://go.dev/doc/tutorial/compile-install","https://gopherforge.app/downloads/go-devops-capstone-20261106.zip"],"reviewAnswer":"Change → verify → deliver → observe → improve","reviewPrompt":"DevOps feedback loop","sections":[{"body":"Suppose a Go API must return a new optional JSON field. Write the observable contract and a compatibility test, inspect the current module/toolchain, build one immutable artifact, deploy it to an isolated environment, check a real request and useful telemetry, then promote the same artifact. A green build does not establish that the deployed route reaches the intended version. Record a source revision, artifact digest, target, rollout outcome and a recovery decision. Feedback from production should change the next test or design, rather than disappear into a chat message.","title":"Follow one change through the whole loop"},{"body":"Before this unit, complete Command line: arguments, exit codes, processes, Git, HTTP and Linux services. Then study Containers and Kubernetes: images, persistent data, contexts, probes and rollouts. The modules lessons explain toolchain pins and build capacity; service-security and SQL lessons cover trust boundaries and transaction ownership. This unit joins those topics into an operational workflow. A disposable local service is enough for the first exercises; paid cloud resources, a public cluster and production credentials are unnecessary.","title":"Use the existing foundation in a deliberate order"},{"body":"Write down a repeated task, its current frequency, failure modes and time cost. A useful first tool may validate a configuration, produce an inventory report or compare desired and observed state. Give it read-only credentials first. Require a reviewable plan before mutation, bounded work, cancellation, structured output and tests for partial failure. Measure whether the tool reduced repeated manual work without creating a new unowned service. Keep a simple script when it remains clear; move to Go when types, testing, concurrency or distribution make the contract easier to maintain.","title":"Choose toil that can be reduced safely"},{"body":"These commands belong on a native development machine in a repository you control. Tests need independent assertions; vet and vulnerability checks answer different questions. A clean run cannot prove operational readiness, secrets hygiene or rollback safety.","code":"go version\ngo env GOMOD GOTOOLCHAIN\ngo test -count=1 ./...\ngo vet ./...\ngo build -trimpath -o ./build/service ./cmd/service","language":"bash","title":"Run a local evidence loop","walkthrough":"Use the repository’s pinned toolchain and an explicitly reviewed working directory. Do not paste deployment or deletion commands into a production shell while exploring this lesson."},{"body":"Create a small Go HTTP service in a disposable native environment. Define one successful request, a bounded shutdown, a health contract and one expected failure. Write a runbook containing the exact environment, observable symptom, first read-only checks, a reversible mitigation and how to verify recovery. Ask another person to follow it without undocumented credentials or shell history. The deliverable is a working feedback loop with evidence, not a claim to have completed every DevOps discipline.","title":"Your first operational contract"},{"body":"Return to this capstone after completing the six DevOps readings. Download the complete lab, including independent tests and its README, from https://gopherforge.app/downloads/go-devops-capstone-20261106.zip. The default main.go below uses httptest recorders: it opens no socket and prints readiness 503, then 204, and version 200 with revision local-review. It can be explored in GopherForge. The optional -serve mode listens only on loopback and belongs in a native development environment. Liveness and readiness express different contracts; a successful health request does not prove a successful business operation.","code":"package main\n\nimport (\n\t\"context\"\n\t\"encoding/json\"\n\t\"errors\"\n\t\"flag\"\n\t\"fmt\"\n\t\"io\"\n\t\"log\"\n\t\"net\"\n\t\"net/http\"\n\t\"net/http/httptest\"\n\t\"os\"\n\t\"os/signal\"\n\t\"strings\"\n\t\"sync/atomic\"\n\t\"syscall\"\n\t\"time\"\n)\n\nvar buildRevision = \"local-review\"\n\nfunc newService(revision string, ready *atomic.Bool) (http.Handler, error) {\n\tif strings.TrimSpace(revision) == \"\" || ready == nil {\n\t\treturn nil, errors.New(\"revision and readiness owner are required\")\n\t}\n\tmux := http.NewServeMux()\n\tmux.HandleFunc(\"GET /livez\", func(w http.ResponseWriter, _ *http.Request) {\n\t\tw.WriteHeader(http.StatusNoContent)\n\t})\n\tmux.HandleFunc(\"GET /readyz\", func(w http.ResponseWriter, _ *http.Request) {\n\t\tif !ready.Load() {\n\t\t\thttp.Error(w, \"not ready\", http.StatusServiceUnavailable)\n\t\t\treturn\n\t\t}\n\t\tw.WriteHeader(http.StatusNoContent)\n\t})\n\tmux.HandleFunc(\"GET /version\", func(w http.ResponseWriter, _ *http.Request) {\n\t\tw.Header().Set(\"Content-Type\", \"application/json\")\n\t\tif err := json.NewEncoder(w).Encode(map[string]string{\"revision\": revision}); err != nil {\n\t\t\tlog.Printf(\"version response: %v\", err)\n\t\t}\n\t})\n\treturn mux, nil\n}\n\nfunc probe(handler http.Handler, method, path string) *httptest.ResponseRecorder {\n\trecorder := httptest.NewRecorder()\n\thandler.ServeHTTP(recorder, httptest.NewRequest(method, path, nil))\n\treturn recorder\n}\n\n// The default demonstration opens no socket: it also works as a local model.\nfunc demonstrate(out io.Writer, revision string) error {\n\tvar ready atomic.Bool\n\thandler, err := newService(revision, &ready)\n\tif err != nil {\n\t\treturn err\n\t}\n\tif _, err := fmt.Fprintln(out, \"not ready:\", probe(handler, \"GET\", \"/readyz\").Code); err != nil {\n\t\treturn err\n\t}\n\tready.Store(true)\n\tif _, err := fmt.Fprintln(out, \"ready:\", probe(handler, \"GET\", \"/readyz\").Code); err != nil {\n\t\treturn err\n\t}\n\tversion := probe(handler, \"GET\", \"/version\")\n\t_, err = fmt.Fprintf(out, \"version: %d %s\", version.Code, version.Body.String())\n\treturn err\n}\n\n// Native development only. This owner joins its HTTP serving goroutine.\nfunc serveOwned(ctx context.Context, listener net.Listener, handler http.Handler, ready *atomic.Bool) error {\n\tserver := &http.Server{\n\t\tHandler: handler, ReadHeaderTimeout: 2 * time.Second,\n\t\tIdleTimeout: 30 * time.Second, WriteTimeout: 5 * time.Second,\n\t\tMaxHeaderBytes: 16 << 10,\n\t}\n\tfinished := make(chan error, 1)\n\tready.Store(true)\n\tgo func() { finished <- server.Serve(listener) }()\n\tselect {\n\tcase err := <-finished:\n\t\tready.Store(false)\n\t\tif errors.Is(err, http.ErrServerClosed) {\n\t\t\treturn nil\n\t\t}\n\t\treturn err\n\tcase <-ctx.Done():\n\t\tready.Store(false)\n\t\tshutdown, cancel := context.WithTimeout(context.Background(), 2*time.Second)\n\t\tdefer cancel()\n\t\terr := server.Shutdown(shutdown)\n\t\tif err != nil {\n\t\t\t_ = server.Close()\n\t\t}\n\t\tserveErr := <-finished\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tif !errors.Is(serveErr, http.ErrServerClosed) {\n\t\t\treturn serveErr\n\t\t}\n\t\treturn nil\n\t}\n}\n\nfunc run(args []string, out io.Writer) error {\n\tflags := flag.NewFlagSet(\"service\", flag.ContinueOnError)\n\tflags.SetOutput(io.Discard)\n\tserve := flags.Bool(\"serve\", false, \"listen in a native development environment\")\n\taddress := flags.String(\"addr\", \"127.0.0.1:8080\", \"explicit loopback address\")\n\trevision := flags.String(\"revision\", buildRevision, \"reported build label\")\n\tif err := flags.Parse(args); err != nil {\n\t\treturn err\n\t}\n\tif flags.NArg() != 0 {\n\t\treturn errors.New(\"unexpected positional argument\")\n\t}\n\tif !*serve {\n\t\treturn demonstrate(out, *revision)\n\t}\n\tvar ready atomic.Bool\n\thandler, err := newService(*revision, &ready)\n\tif err != nil {\n\t\treturn err\n\t}\n\thost, _, err := net.SplitHostPort(*address)\n\tip := net.ParseIP(host)\n\tif err != nil || ip == nil || !ip.IsLoopback() {\n\t\treturn errors.New(\"this lab listens only on an explicit loopback IP\")\n\t}\n\tlistener, err := net.Listen(\"tcp\", *address)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer listener.Close()\n\tctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM)\n\tdefer stop()\n\treturn serveOwned(ctx, listener, handler, &ready)\n}\n\nfunc main() {\n\tif err := run(os.Args[1:], os.Stdout); err != nil {\n\t\tfmt.Fprintln(os.Stderr, err)\n\t\tos.Exit(1)\n\t}\n}\n","language":"go","title":"Run the capstone model","walkthrough":"Run without flags first. newService owns route contracts, demonstrate drives readiness explicitly, and serveOwned owns the native HTTP serving goroutine. On cancellation it clears readiness, bounds HTTP shutdown to two seconds, closes on timeout and joins Serve. Application workers, hijacked connections and deployment traffic draining need their own owners; this example does not establish their shutdown. A revision label, which -revision can override, is not proof of binary identity."},{"body":"In the downloaded lab, run ./verify.sh from a native development machine or a clean CI checkout with a reviewed Go 1.27 toolchain and C compiler for the race detector. The independent tests check response contracts, invalid input, readiness and native cancellation. Retain the generated executable, source manifest, toolchain, build information and executable digest together. Promote those exact bytes after verification; a later rebuild needs its own evidence. Source and artifact digests identify bytes; they are not signatures or trusted provenance attestations. Vulnerability checks, signing policy and deployment decisions remain separate gates.","code":"#!/usr/bin/env bash\nset -euo pipefail\ncd \"$(dirname \"$0\")\"\nexport GOTOOLCHAIN=local\nmkdir -p build\ngo version > build/toolchain.txt\ngo test -race -count=1 ./...\ngo vet ./...\nshasum -a 256 main.go main_test.go go.mod verify.sh > build/sources.sha256\nsource_id=\"$(shasum -a 256 build/sources.sha256 | cut -d ' ' -f 1)\"\ngo build -trimpath -ldflags \"-X main.buildRevision=$source_id\" -o build/service .\nshasum -a 256 build/service > build/service.sha256\ngo version -m build/service > build/buildinfo.txt\nprintf 'Verified one artifact. Review build/service.sha256 and retain these exact bytes.\\n'\n","language":"bash","title":"Retain one verified artifact","walkthrough":"The script stops on a failed test, race check, vet or build. It writes evidence into build/, embeds a source-manifest label and hashes the resulting native executable. These shell commands and -race do not run inside the app or browser WASI sandbox. The script performs no deployment."},{"body":"The lab README gives exact commands and expected results. Add an optional service field while retaining the old revision contract: first observe a failing independent test, then fix the code and rerun verification. Demonstrate 503 → 204 → 503 readiness, an unknown route and rejected invalid configuration. Run the native cancellation test under the race detector. Record artifact identity and target, define an SLI event/window, and write a runbook another person can follow: symptom, read-only checks, reversible mitigation and recovery evidence. Describe compatibility and accepted-data handling before choosing rollback. The lab has no database or production load balancer, so it cannot prove data-migration safety, a production rollout or an SLO from a few local requests.","title":"Finish the capstone with evidence"},{"body":"Complete file from the multi-file capstone. It is included in the course download for offline reading and copying. The default model runs in WASI; native server, race-detector and infrastructure exercises require your own disposable native environment. The linked ZIP is an optional convenience, not a prerequisite for reading these files offline.","code":"# Go DevOps capstone: prove one service change\n\nComplete the six GopherForge DevOps readings, then return to this lab. The goal is a small, reviewable delivery loop with evidence. Go builds the service and its checks; deployment, monitoring and recovery still need explicit owners.\n\n## Run the local model\n\nUse Go 1.27 with the toolchain version recorded in your evidence. The project has no third-party dependencies. From this directory:\n\n```sh\ngo run .\n```\n\nExpected output:\n\n```text\nnot ready: 503\nready: 204\nversion: 200 {\"revision\":\"local-review\"}\n```\n\nThe default mode uses `httptest` recorders and opens no network socket. Copy `main.go` into GopherForge to explore that mode. Listening, process signals, shell commands and the race detector belong in a native development environment, outside the app/browser sandbox.\n\n## Verify and retain one artifact\n\nOn a native machine with a supported C compiler for Go's race detector:\n\n```sh\n./verify.sh\n./build/service\ngo version -m ./build/service\nshasum -a 256 ./build/service\n```\n\nThe script runs independent contract tests, a race check and `go vet`, records the toolchain and a source manifest, and builds one executable. It embeds the manifest digest in `/version` and records the binary digest. Keep `build/toolchain.txt`, `build/sources.sha256`, `build/buildinfo.txt` and `build/service.sha256` with that exact executable. A source digest is an identifier, not a signature or a trusted build attestation. The `-revision` flag can override the label; the label alone never proves binary identity.\n\nThe same `./verify.sh` command can be a CI step after a clean checkout and installation of the reviewed Go/C toolchains. Restrict the job to the permissions it needs. A vulnerability check, provenance/signing policy and deployment approval are separate gates; this script does not establish them.\n\n## Inspect the native service\n\nIn one terminal, run the verified artifact on loopback:\n\n```sh\n./build/service -serve -addr 127.0.0.1:8080\n```\n\nIn another terminal:\n\n```sh\ncurl --fail --silent --show-error http://127.0.0.1:8080/version\ncurl --fail --silent --show-error -o /dev/null -w '%{http_code}\\n' http://127.0.0.1:8080/readyz\ncurl --silent --show-error -o /dev/null -w '%{http_code}\\n' http://127.0.0.1:8080/missing\n```\n\nExpect the recorded revision, `204`, and `404`. Stop the first terminal with Ctrl-C. The server owner clears readiness, gives HTTP shutdown two seconds, closes on timeout and joins its serving goroutine. It does not own hypothetical application workers or hijacked connections. A real deployment also needs traffic draining and explicit ownership of those resources. The test suite checks readiness transitions directly; this lab does not simulate a production load balancer.\n\n## Acceptance checklist\n\n1. Add an optional `service` field to `/version`. Keep an independent test for the existing `revision` field so older clients remain compatible. Change the test expectation first, observe failure, then implement the field and rerun verification.\n2. Demonstrate invalid configuration, an unknown route and readiness changing from `503` to `204` and back. Explain why liveness and readiness are different contracts.\n3. Run the native cancellation test under `-race`. Record the process exit and explain which goroutine is joined, the shutdown deadline and what still needs a separate owner.\n4. Record the exact verified binary digest and target environment. Promote those bytes; rebuilding for a later environment creates a different artifact that needs new evidence. Never use the `/version` label as a substitute for the artifact digest.\n5. Draft a runbook with an observable symptom, first read-only checks, a reversible mitigation and a recovery check. Specify the success/error event and time window you would measure for an SLI; three local requests do not establish an SLO.\n6. Write a recovery decision for the optional-field change. Explain compatibility and accepted-data handling. This lab has no database; it cannot prove that rolling back a real data migration preserves writes. Have another person follow the runbook in an environment you control.\n\nKeep a short evidence file with commands, observed outcomes, source and artifact identities, target and remaining limits. A green test run is one input to a release decision. It is not evidence of a production rollout or a complete DevOps qualification.\n","language":"markdown","title":"Offline capstone source: README.md","walkthrough":"Start with the stated acceptance contract and prerequisites. The documented commands form one repeatable evidence loop; local success still needs the separate isolated service deployment and recovery checks described in this lesson."},{"body":"Complete file from the multi-file capstone. It is included in the course download for offline reading and copying. The default model runs in WASI; native server, race-detector and infrastructure exercises require your own disposable native environment. The linked ZIP is an optional convenience, not a prerequisite for reading these files offline.","code":"module example.com/gopherforge-devops-capstone\n\ngo 1.27.0\n","language":"gomod","title":"Offline capstone source: go.mod","walkthrough":"The module path identifies this standalone exercise and the Go directive declares its language baseline. There are no third-party requirements, so the example can be inspected and compiled without fetching provider or deployment SDKs."},{"body":"Complete file from the multi-file capstone. It is included in the course download for offline reading and copying. The default model runs in WASI; native server, race-detector and infrastructure exercises require your own disposable native environment. The linked ZIP is an optional convenience, not a prerequisite for reading these files offline.","code":"package main\n\nimport (\n\t\"context\"\n\t\"encoding/json\"\n\t\"errors\"\n\t\"flag\"\n\t\"fmt\"\n\t\"io\"\n\t\"log\"\n\t\"net\"\n\t\"net/http\"\n\t\"net/http/httptest\"\n\t\"os\"\n\t\"os/signal\"\n\t\"strings\"\n\t\"sync/atomic\"\n\t\"syscall\"\n\t\"time\"\n)\n\nvar buildRevision = \"local-review\"\n\nfunc newService(revision string, ready *atomic.Bool) (http.Handler, error) {\n\tif strings.TrimSpace(revision) == \"\" || ready == nil {\n\t\treturn nil, errors.New(\"revision and readiness owner are required\")\n\t}\n\tmux := http.NewServeMux()\n\tmux.HandleFunc(\"GET /livez\", func(w http.ResponseWriter, _ *http.Request) {\n\t\tw.WriteHeader(http.StatusNoContent)\n\t})\n\tmux.HandleFunc(\"GET /readyz\", func(w http.ResponseWriter, _ *http.Request) {\n\t\tif !ready.Load() {\n\t\t\thttp.Error(w, \"not ready\", http.StatusServiceUnavailable)\n\t\t\treturn\n\t\t}\n\t\tw.WriteHeader(http.StatusNoContent)\n\t})\n\tmux.HandleFunc(\"GET /version\", func(w http.ResponseWriter, _ *http.Request) {\n\t\tw.Header().Set(\"Content-Type\", \"application/json\")\n\t\tif err := json.NewEncoder(w).Encode(map[string]string{\"revision\": revision}); err != nil {\n\t\t\tlog.Printf(\"version response: %v\", err)\n\t\t}\n\t})\n\treturn mux, nil\n}\n\nfunc probe(handler http.Handler, method, path string) *httptest.ResponseRecorder {\n\trecorder := httptest.NewRecorder()\n\thandler.ServeHTTP(recorder, httptest.NewRequest(method, path, nil))\n\treturn recorder\n}\n\n// The default demonstration opens no socket: it also works as a local model.\nfunc demonstrate(out io.Writer, revision string) error {\n\tvar ready atomic.Bool\n\thandler, err := newService(revision, &ready)\n\tif err != nil {\n\t\treturn err\n\t}\n\tif _, err := fmt.Fprintln(out, \"not ready:\", probe(handler, \"GET\", \"/readyz\").Code); err != nil {\n\t\treturn err\n\t}\n\tready.Store(true)\n\tif _, err := fmt.Fprintln(out, \"ready:\", probe(handler, \"GET\", \"/readyz\").Code); err != nil {\n\t\treturn err\n\t}\n\tversion := probe(handler, \"GET\", \"/version\")\n\t_, err = fmt.Fprintf(out, \"version: %d %s\", version.Code, version.Body.String())\n\treturn err\n}\n\n// Native development only. This owner joins its HTTP serving goroutine.\nfunc serveOwned(ctx context.Context, listener net.Listener, handler http.Handler, ready *atomic.Bool) error {\n\tserver := &http.Server{\n\t\tHandler: handler, ReadHeaderTimeout: 2 * time.Second,\n\t\tIdleTimeout: 30 * time.Second, WriteTimeout: 5 * time.Second,\n\t\tMaxHeaderBytes: 16 << 10,\n\t}\n\tfinished := make(chan error, 1)\n\tready.Store(true)\n\tgo func() { finished <- server.Serve(listener) }()\n\tselect {\n\tcase err := <-finished:\n\t\tready.Store(false)\n\t\tif errors.Is(err, http.ErrServerClosed) {\n\t\t\treturn nil\n\t\t}\n\t\treturn err\n\tcase <-ctx.Done():\n\t\tready.Store(false)\n\t\tshutdown, cancel := context.WithTimeout(context.Background(), 2*time.Second)\n\t\tdefer cancel()\n\t\terr := server.Shutdown(shutdown)\n\t\tif err != nil {\n\t\t\t_ = server.Close()\n\t\t}\n\t\tserveErr := <-finished\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tif !errors.Is(serveErr, http.ErrServerClosed) {\n\t\t\treturn serveErr\n\t\t}\n\t\treturn nil\n\t}\n}\n\nfunc run(args []string, out io.Writer) error {\n\tflags := flag.NewFlagSet(\"service\", flag.ContinueOnError)\n\tflags.SetOutput(io.Discard)\n\tserve := flags.Bool(\"serve\", false, \"listen in a native development environment\")\n\taddress := flags.String(\"addr\", \"127.0.0.1:8080\", \"explicit loopback address\")\n\trevision := flags.String(\"revision\", buildRevision, \"reported build label\")\n\tif err := flags.Parse(args); err != nil {\n\t\treturn err\n\t}\n\tif flags.NArg() != 0 {\n\t\treturn errors.New(\"unexpected positional argument\")\n\t}\n\tif !*serve {\n\t\treturn demonstrate(out, *revision)\n\t}\n\tvar ready atomic.Bool\n\thandler, err := newService(*revision, &ready)\n\tif err != nil {\n\t\treturn err\n\t}\n\thost, _, err := net.SplitHostPort(*address)\n\tip := net.ParseIP(host)\n\tif err != nil || ip == nil || !ip.IsLoopback() {\n\t\treturn errors.New(\"this lab listens only on an explicit loopback IP\")\n\t}\n\tlistener, err := net.Listen(\"tcp\", *address)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer listener.Close()\n\tctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM)\n\tdefer stop()\n\treturn serveOwned(ctx, listener, handler, &ready)\n}\n\nfunc main() {\n\tif err := run(os.Args[1:], os.Stdout); err != nil {\n\t\tfmt.Fprintln(os.Stderr, err)\n\t\tos.Exit(1)\n\t}\n}\n","language":"go","title":"Offline capstone source: main.go","walkthrough":"Trace the program from its bounded input through validation to the reported outcome. Read the explicit failure paths and ownership rules before changing the success case. The code models a delivery contract without acquiring real deployment authority."},{"body":"Complete file from the multi-file capstone. It is included in the course download for offline reading and copying. The default model runs in WASI; native server, race-detector and infrastructure exercises require your own disposable native environment. The linked ZIP is an optional convenience, not a prerequisite for reading these files offline.","code":"package main\n\nimport (\n\t\"bytes\"\n\t\"context\"\n\t\"encoding/json\"\n\t\"errors\"\n\t\"net\"\n\t\"net/http\"\n\t\"sync/atomic\"\n\t\"testing\"\n\t\"time\"\n)\n\nfunc TestReadinessAndVersionContract(t *testing.T) {\n\tvar ready atomic.Bool\n\thandler, err := newService(\"reviewed-a1\", &ready)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tif got := probe(handler, \"GET\", \"/readyz\").Code; got != 503 {\n\t\tt.Fatal(got)\n\t}\n\tif got := probe(handler, \"GET\", \"/livez\").Code; got != 204 {\n\t\tt.Fatal(got)\n\t}\n\tready.Store(true)\n\tif got := probe(handler, \"GET\", \"/readyz\").Code; got != 204 {\n\t\tt.Fatal(got)\n\t}\n\tversion := probe(handler, \"GET\", \"/version\")\n\tvar payload map[string]string\n\tif err := json.Unmarshal(version.Body.Bytes(), &payload); err != nil {\n\t\tt.Fatal(err)\n\t}\n\tif version.Code != 200 || payload[\"revision\"] != \"reviewed-a1\" || version.Header().Get(\"Content-Type\") != \"application/json\" {\n\t\tt.Fatal(version, payload)\n\t}\n\tif got := probe(handler, \"POST\", \"/version\").Code; got != 405 {\n\t\tt.Fatal(got)\n\t}\n\tif got := probe(handler, \"GET\", \"/missing\").Code; got != 404 {\n\t\tt.Fatal(got)\n\t}\n\tready.Store(false)\n\tif got := probe(handler, \"GET\", \"/readyz\").Code; got != 503 {\n\t\tt.Fatal(got)\n\t}\n}\n\ntype failedWriter struct{}\n\nfunc (failedWriter) Write([]byte) (int, error) { return 0, errors.New(\"output unavailable\") }\nfunc TestInvalidConfigurationAndOutputFailure(t *testing.T) {\n\tvar ready atomic.Bool\n\tif _, err := newService(\" \", &ready); err == nil {\n\t\tt.Fatal(\"blank revision accepted\")\n\t}\n\tif _, err := newService(\"a1\", nil); err == nil {\n\t\tt.Fatal(\"missing owner accepted\")\n\t}\n\tfor _, args := range [][]string{{\"-typo\"}, {\"extra\"}, {\"-serve\", \"-addr\", \"0.0.0.0:8080\"}} {\n\t\tif err := run(args, &bytes.Buffer{}); err == nil {\n\t\t\tt.Fatal(\"invalid input accepted\", args)\n\t\t}\n\t}\n\tif err := demonstrate(failedWriter{}, \"a1\"); err == nil {\n\t\tt.Fatal(\"output failure hidden\")\n\t}\n\tvar out bytes.Buffer\n\tif err := run(nil, &out); err != nil {\n\t\tt.Fatal(err)\n\t}\n\tif out.String() != \"not ready: 503\\nready: 204\\nversion: 200 {\\\"revision\\\":\\\"local-review\\\"}\\n\" {\n\t\tt.Fatal(out.String())\n\t}\n}\n\nfunc TestNativeServerJoinsAfterCancellation(t *testing.T) {\n\tlistener, err := net.Listen(\"tcp\", \"127.0.0.1:0\")\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tdefer listener.Close()\n\tvar ready atomic.Bool\n\thandler, err := newService(\"native-test\", &ready)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tctx, cancel := context.WithCancel(context.Background())\n\tdefer cancel()\n\tfinished := make(chan error, 1)\n\tgo func() { finished <- serveOwned(ctx, listener, handler, &ready) }()\n\tclient := &http.Client{Timeout: 2 * time.Second}\n\tresponse, err := client.Get(\"http://\" + listener.Addr().String() + \"/version\")\n\tif err != nil {\n\t\tcancel()\n\t\tt.Fatal(err)\n\t}\n\tresponse.Body.Close()\n\tif response.StatusCode != 200 {\n\t\tt.Fatal(response.StatusCode)\n\t}\n\tcancel()\n\tselect {\n\tcase err := <-finished:\n\t\tif err != nil || ready.Load() {\n\t\t\tt.Fatal(err, ready.Load())\n\t\t}\n\tcase <-time.After(4 * time.Second):\n\t\tt.Fatal(\"server owner did not join\")\n\t}\n}\n","language":"go","title":"Offline capstone source: main_test.go","walkthrough":"The tests exercise independent success and failure cases against the public behavior of the model. Change an input or break an invariant to see a real failure, then restore the contract and rerun; a green result only establishes the behavior covered here."},{"body":"Complete file from the multi-file capstone. It is included in the course download for offline reading and copying. The default model runs in WASI; native server, race-detector and infrastructure exercises require your own disposable native environment. The linked ZIP is an optional convenience, not a prerequisite for reading these files offline.","code":"#!/usr/bin/env bash\nset -euo pipefail\ncd \"$(dirname \"$0\")\"\nexport GOTOOLCHAIN=local\nmkdir -p build\ngo version > build/toolchain.txt\ngo test -race -count=1 ./...\ngo vet ./...\nshasum -a 256 main.go main_test.go go.mod verify.sh > build/sources.sha256\nsource_id=\"$(shasum -a 256 build/sources.sha256 | cut -d ' ' -f 1)\"\ngo build -trimpath -ldflags \"-X main.buildRevision=$source_id\" -o build/service .\nshasum -a 256 build/service > build/service.sha256\ngo version -m build/service > build/buildinfo.txt\nprintf 'Verified one artifact. Review build/service.sha256 and retain these exact bytes.\\n'\n","language":"bash","title":"Offline capstone source: verify.sh","walkthrough":"Run these checks from the exercise directory on an owned native environment with Go installed. The script stops on a failed check and records verification evidence. It never grants release permissions or proves the state of an external deployment."}],"takeaway":"Connect a service change to tests, delivery, operation and feedback, and choose a small automation project with a measurable outcome.","title":"DevOps is a delivery feedback loop; Go builds its tools","unitID":"devops","wrongAnswers":["Change → rebuild separately for production → stop after a green build","Add tools → grant broad privileges → omit recovery verification"]},{"conceptTag":"devops.safe-cli","designGuide":{"cautions":["Reject unknown input and apply independent byte, target, concurrency and time budgets. Validate and test a dry run before introducing writes."],"cost":"Automation needs explicit ownership, bounded privileges, tests and recovery evidence; a shorter command is not sufficient.","family":"Go for DevOps and reliability","flow":["Parse bounded input","Build a read-only plan","Run owned bounded work","Report an explicit outcome"],"ratings":[],"strengths":["Design a Go command with bounded input, machine-readable output, explicit exit status and cancellation ownership.","Make changes reviewable and verify the result against the original contract."]},"hint":"Validate at the boundary, before any side effect.","id":"devops.safe-cli","introduction":"A script becomes infrastructure when other programs rely on it. Define its input, output, exit codes and side effects before adding concurrency or cloud APIs. A read-only inventory tool is a useful first project because failure can be tested without changing a real system.","nuance":"Reject unknown input and apply independent byte, target, concurrency and time budgets. Validate and test a dry run before introducing writes.","objective":"Design a Go command with bounded input, machine-readable output, explicit exit status and cancellation ownership.","question":"What should happen before a misspelled safety field reaches the operational client?","references":["https://pkg.go.dev/flag","https://pkg.go.dev/os/exec#CommandContext","https://pkg.go.dev/os/signal#NotifyContext","https://pkg.go.dev/encoding/json#Decoder.DisallowUnknownFields"],"reviewAnswer":"Reject unknown input before any side effect","reviewPrompt":"Operational CLI input","sections":[{"body":"Keep machine-readable results on stdout and diagnostic messages on stderr. Return a nonzero exit code for an unsuccessful operation; an empty result is different from a failed request. Reject unknown flags and configuration fields so a misspelled safety option cannot silently do nothing. Limit input bytes, target count, response bytes, concurrency and total elapsed time independently. A timeout does not limit how much input is read, and a worker limit does not bound a queue.","title":"Specify what callers can depend on"},{"body":"This complete program validates a small JSON inventory and emits one JSON report. It performs no network calls or writes. The fixed input makes it runnable in the app/browser as a teaching model. Unknown fields, trailing documents, excessive bytes, duplicate targets and empty inventories fail before producing a success report.","code":"package main\n\nimport (\n \"encoding/json\"\n \"errors\"\n \"fmt\"\n \"io\"\n \"strings\"\n)\n\ntype Input struct { Targets []string `json:\"targets\"` }\ntype Report struct { Mode string `json:\"mode\"`; Count int `json:\"count\"` }\nfunc inspect(r io.Reader, w io.Writer) error {\n data, err := io.ReadAll(io.LimitReader(r, 4097))\n if err != nil { return err }\n if len(data) > 4096 { return errors.New(\"input exceeds 4096 bytes\") }\n dec := json.NewDecoder(strings.NewReader(string(data)))\n dec.DisallowUnknownFields()\n var input Input\n if err := dec.Decode(&input); err != nil { return err }\n var extra any\n if err := dec.Decode(&extra); err != io.EOF { return errors.New(\"expected one JSON document\") }\n if len(input.Targets) == 0 || len(input.Targets) > 20 { return errors.New(\"use 1-20 targets\") }\n seen := map[string]bool{}\n for _, target := range input.Targets {\n  if target == \"\" || strings.ContainsAny(target, \" \\t\\r\\n\") || seen[target] { return errors.New(\"invalid or repeated target\") }\n  seen[target] = true\n }\n return json.NewEncoder(w).Encode(Report{Mode: \"dry-run\", Count: len(input.Targets)})\n}\nfunc main() {\n err := inspect(strings.NewReader(`{\"targets\":[\"api-a\",\"api-b\"]}`), writer{})\n if err != nil { fmt.Println(\"error:\", err) }\n}\ntype writer struct{}\nfunc (writer) Write(p []byte) (int, error) { return fmt.Print(string(p)) }\n","language":"go","title":"A bounded, deterministic inventory model","walkthrough":"Expected output: {\"mode\":\"dry-run\",\"count\":2}. The writer deliberately demonstrates io.Writer injection. Tests can supply bytes.Buffer and a reader that returns an error, without redirecting process-global stdout."},{"body":"In a real native CLI, parse flags with a dedicated flag.FlagSet, pass os.Stdin and injected stdout/stderr into a run function, and call os.Exit only in main after owned resources have been closed. Use signal.NotifyContext for the top-level interrupt, derive operation deadlines, and join workers before returning. Keep this process/signal layer outside the reusable planning package. It is not available as an arbitrary OS shell in the app’s WASI sandbox.","title":"Add native process behavior at the edge"},{"body":"When a reviewed native task truly needs a subprocess, pass an executable and an argument slice to exec.CommandContext. Never concatenate inventory values into sh -c. Use an allowlisted executable, a known working directory, a controlled environment and bounded output. Command cancellation alone may not end every descendant process: process-group cleanup and platform-specific behavior require explicit tests. A redacted log should identify the operation and result without exposing access tokens or user-controlled terminal escapes.","title":"Treat shell execution as a separate capability"},{"body":"Test valid input, an unknown field, two JSON documents, an over-budget reader, a duplicate target and a failing output writer. Assert both exit behavior and whether a success record was written. Next add a fake client that blocks until context cancellation; verify that the command returns and all workers exit. Run an actual local smoke test against a disposable target before adding any apply mode. A dry-run flag is credible only when tests prove it cannot reach mutation methods.","title":"Exercise failure as part of the interface"}],"takeaway":"Design a Go command with bounded input, machine-readable output, explicit exit status and cancellation ownership.","title":"Build a small operational CLI with explicit boundaries","unitID":"devops","wrongAnswers":["Ignore it and assume the default action is safe","Accept it as a shell command fragment"]},{"conceptTag":"devops.reconciliation","designGuide":{"cautions":["A stale plan must be rejected and regenerated from a fresh observation. Use server-side preconditions; client-side checks alone cannot prevent a concurrent write."],"cost":"Automation needs explicit ownership, bounded privileges, tests and recovery evidence; a shorter command is not sufficient.","family":"Go for DevOps and reliability","flow":["Observe version and owner","Plan the intended fields","Apply with a precondition","Read back and converge"],"ratings":[],"strengths":["Separate observation, planning and application; use a version precondition and make a repeated successful reconciliation converge.","Make changes reviewable and verify the result against the original contract."]},"hint":"The plan is evidence about a particular observation.","id":"devops.reconciliation","introduction":"A controller repeatedly compares desired state with observed state. Network retries and concurrent operators make “run this command once” an unreliable model. A useful plan says exactly what will change, from which observed version, and what evidence will establish convergence.","nuance":"A stale plan must be rejected and regenerated from a fresh observation. Use server-side preconditions; client-side checks alone cannot prevent a concurrent write.","objective":"Separate observation, planning and application; use a version precondition and make a repeated successful reconciliation converge.","question":"A resource changed after you generated the plan. What is the next action?","references":["https://kubernetes.io/docs/reference/using-api/api-concepts/","https://kubernetes.io/docs/reference/using-api/server-side-apply/","https://pkg.go.dev/context"],"reviewAnswer":"Observe → plan → apply if version matches","reviewPrompt":"Reconciliation precondition","sections":[{"body":"Represent an observed object, its version and the intended fields as data. Planning should be deterministic and read-only. Review the resource identifier, environment, version, desired fields and blast radius before applying. A plan computed for one namespace or cloud account must not silently apply to another. Re-read state after a conflict rather than forcing the old plan.","title":"Make observation and mutation separate operations"},{"body":"The example changes a replica count only if the observed version still matches. Applying an old change a second time returns a conflict. Planning again against the new observation finds no work. That is convergence; it does not mean every repeated API request is harmless.","code":"package main\n\nimport (\n \"errors\"\n \"fmt\"\n)\nvar ErrConflict = errors.New(\"observed version changed\")\ntype State struct { Version, Replicas int }\ntype Change struct { ExpectedVersion, Replicas int }\nfunc plan(desired int, observed State) (*Change, error) {\n if desired < 0 || desired > 20 { return nil, errors.New(\"replicas outside budget\") }\n if observed.Replicas == desired { return nil, nil }\n return &Change{ExpectedVersion: observed.Version, Replicas: desired}, nil\n}\nfunc apply(state *State, change Change) error {\n if state.Version != change.ExpectedVersion { return ErrConflict }\n state.Replicas = change.Replicas\n state.Version++\n return nil\n}\nfunc main() {\n state := State{Version: 41, Replicas: 2}\n change, _ := plan(3, state)\n fmt.Println(\"planned\", change.ExpectedVersion, change.Replicas)\n fmt.Println(\"applied\", apply(&state, *change), state)\n fmt.Println(\"stale\", errors.Is(apply(&state, *change), ErrConflict))\n again, _ := plan(3, state)\n fmt.Println(\"converged\", again == nil)\n}\n","language":"go","title":"An in-memory compare-and-swap exercise","walkthrough":"Expected lines: planned 41 3; applied <nil> {42 3}; stale true; converged true. This map-free model has no external infrastructure and can run in the app. A real API needs server-side version checks; a local if statement around two HTTP requests is not atomic."},{"body":"A full-object replacement can erase another controller’s fields. Define ownership and use the API’s supported preconditions and patch semantics. In Kubernetes, resourceVersion is an opaque string, not a client-side integer counter; server-side apply also tracks field ownership. The integer here is only a teaching model. Conflicts are evidence of a newer observation, not permission to remove another writer’s changes.","title":"Reconcile only the fields you own"},{"body":"After a transport timeout, a write may have committed even though its response was lost. Read the authoritative object or query by a stable operation identity before trying a non-idempotent operation again. Retry only classified transient failures, with cancellation, a total deadline, a maximum attempt count and jitter where appropriate. An error caused by invalid configuration or authorization does not become valid after sleeping. Stop an automated loop when it cannot establish a safe outcome.","title":"Retry with budgets and outcome reconciliation"},{"body":"Write tests where a second writer advances Version between plan and apply. Verify that the stale attempt changes neither replicas nor version. Test a no-op plan, an invalid desired value and a successful retry after a fresh observation. Extend the model with an environment identifier and prove that a plan for staging cannot mutate production. Only then adapt the interface to a disposable local API, using least-privilege credentials and an explicit apply action.","title":"Practice a concurrent operator"}],"takeaway":"Separate observation, planning and application; use a version precondition and make a repeated successful reconciliation converge.","title":"Reconcile desired state without overwriting a newer observation","unitID":"devops","wrongAnswers":["Force the old complete object over the newer version","Retry forever without reading the current object"]},{"conceptTag":"devops.delivery-artifacts","designGuide":{"cautions":["Tie trusted verification and approval to the exact artifact digest. A mutable tag, a source commit or a self-reported success flag is not equivalent evidence."],"cost":"Automation needs explicit ownership, bounded privileges, tests and recovery evidence; a shorter command is not sufficient.","family":"Go for DevOps and reliability","flow":["Verify without release secrets","Record immutable identity","Approve the exact target","Promote and check behavior"],"ratings":[],"strengths":["Bind verification evidence and release approval to an immutable artifact, then distinguish application rollout from data recovery.","Make changes reviewable and verify the result against the original contract."]},"hint":"Approval and test evidence refer to specific bytes.","id":"devops.delivery-artifacts","introduction":"A source commit, mutable image tag and built binary are different identities. A pipeline can test one artifact and accidentally deploy another. Make every promotion name the exact digest already verified, and keep the build environment and target architecture visible.","nuance":"Tie trusted verification and approval to the exact artifact digest. A mutable tag, a source commit or a self-reported success flag is not equivalent evidence.","objective":"Bind verification evidence and release approval to an immutable artifact, then distinguish application rollout from data recovery.","question":"Which release identity should promotion use after verification?","references":["https://docs.github.com/en/actions/reference/security/secure-use","https://go.dev/doc/security/vuln/","https://docs.docker.com/dhi/core-concepts/digests/"],"reviewAnswer":"Promote the exact verified artifact digest","reviewPrompt":"Artifact promotion identity","sections":[{"body":"On an untrusted change, run formatting/lint rules, unit and integration tests, vet and the repository’s pinned vulnerability check without release credentials. Build the supported target with the pinned Go toolchain and record the commit, module sums, tool versions and artifact digest. A cache hit is useful but does not replace a check that the contract requires. A vulnerability check has a dated database and scope; it is not proof that the service is secure.","title":"Define a small pipeline with independent gates"},{"body":"The function verifies both the artifact bytes and the digest attached to the required evidence. The booleans stand for outcomes from a trusted verification system; accepting untrusted JSON that says tests=true is not a secure gate. The model performs no publishing or deployment.","code":"package main\n\nimport (\n \"crypto/sha256\"\n \"encoding/hex\"\n \"errors\"\n \"fmt\"\n)\ntype Evidence struct { Digest string; Tests, Vet, VulnerabilityCheck bool }\nfunc promote(artifact []byte, evidence Evidence, approvedDigest string) error {\n actual := sha256.Sum256(artifact)\n digest := hex.EncodeToString(actual[:])\n if len(approvedDigest) != 64 || digest != approvedDigest || evidence.Digest != approvedDigest { return errors.New(\"artifact identity mismatch\") }\n if !evidence.Tests || !evidence.Vet || !evidence.VulnerabilityCheck { return errors.New(\"required gate failed\") }\n return nil\n}\nfunc main() {\n artifact := []byte(\"reviewed release artifact\")\n hash := sha256.Sum256(artifact)\n digest := hex.EncodeToString(hash[:])\n evidence := Evidence{Digest: digest, Tests: true, Vet: true, VulnerabilityCheck: true}\n fmt.Println(\"approved\", promote(artifact, evidence, digest))\n fmt.Println(\"changed\", promote([]byte(\"rebuilt differently\"), evidence, digest))\n evidence.Tests = false\n fmt.Println(\"failed gate\", promote(artifact, evidence, digest))\n}\n","language":"go","title":"A digest-bound promotion model","walkthrough":"Expected output: approved <nil>; changed artifact identity mismatch; failed gate required gate failed. Replace the artifact bytes after approval to see why rebuilding during promotion breaks the tested-artifact contract."},{"body":"Use read-only repository access for normal checks. Give the publishing/deployment job only its required permissions and target, with environment approval where the repository requires it. Prefer short-lived workload identity over a permanent cloud key when the provider supports it. Pin third-party actions to reviewed full commit SHAs, review updates and keep untrusted pull-request code away from privileged runners and secrets. An immutable action reference does not itself audit its implementation.","title":"Scope credentials to the job that needs them"},{"body":"Deploy the same image digest to a disposable environment, confirm readiness and exercise an end-to-end request through the real route. Observe a representative workload before promotion; a successful container start alone does not show API compatibility. A later production promotion needs its own target/digest check, ownership and recovery conditions. Retain the previous image, configuration references, accepted-write boundary and migration state without copying secrets into a public build log.","title":"Promote, observe and retain recovery evidence"},{"body":"In a local repository, produce a binary and a small manifest. Change its bytes after generating the manifest and assert rejection. Fail one test gate and assert that the deployment client is never called. Add an approval for a staging target and reject reuse for another environment. Then rehearse an old-binary/new-schema compatibility failure. Container-registry and Kubernetes lessons provide the actual native commands; this lesson defines the evidence those commands must preserve.","title":"Build a reviewable local release exercise"}],"takeaway":"Bind verification evidence and release approval to an immutable artifact, then distinguish application rollout from data recovery.","title":"CI/CD: build once, verify the digest, promote the same artifact","unitID":"devops","wrongAnswers":["A tag permanently authenticates every future image","Rebuilding always produces byte-identical artifacts"]},{"conceptTag":"devops.slo-burn","designGuide":{"cautions":["No observations mean missing evidence, not demonstrated health. Define eligible events and require appropriate sustained and recent signals before alerting."],"cost":"Automation needs explicit ownership, bounded privileges, tests and recovery evidence; a shorter command is not sufficient.","family":"Go for DevOps and reliability","flow":["Define eligible user outcomes","Measure bad and total events","Compare sustained and recent burn","Respond and verify recovery"],"ratings":[],"strengths":["Define eligible events, compute error-budget burn and require both recent and sustained evidence before paging.","Make changes reviewable and verify the result against the original contract."]},"hint":"A ratio needs a valid, meaningful denominator.","id":"devops.slo-burn","introduction":"An SLI measures a user-relevant outcome; an SLO defines the intended level over a stated window. Error-budget burn relates the observed bad-event fraction to the allowed fraction. It can connect delivery decisions to reliability evidence more usefully than paging on every CPU spike.","nuance":"No observations mean missing evidence, not demonstrated health. Define eligible events and require appropriate sustained and recent signals before alerting.","objective":"Define eligible events, compute error-budget burn and require both recent and sustained evidence before paging.","question":"What does error-budget burn compare?","references":["https://sre.google/workbook/alerting-on-slos/","https://sre.google/workbook/implementing-slos/","https://prometheus.io/docs/practices/instrumentation/"],"reviewAnswer":"Bad fraction ÷ allowed fraction","reviewPrompt":"Error-budget burn","sections":[{"body":"For a request-driven API, state which requests are eligible, what counts as bad, the latency boundary if any and the measurement point. A timeout observed by the caller may be invisible in a server’s completed-request counter. Do not exclude difficult traffic just to improve the number. Business rejections, client cancellation and internal failures need an explicit classification agreed with the service contract. Version that definition when it changes.","title":"Write the denominator before the dashboard"},{"body":"For target 99.9%, the allowed bad-event fraction is 0.001. An observed 2% bad-event fraction burns that budget at about 20 times its sustainable rate. The example requires both windows to pass the configured threshold, and rejects an empty denominator rather than calling missing telemetry healthy. The chosen threshold is an exercise input, not a universal paging policy.","code":"package main\n\nimport (\n \"errors\"\n \"fmt\"\n \"math\"\n)\ntype Window struct { Total, Bad uint64 }\nfunc burn(w Window, target float64) (float64, error) {\n if math.IsNaN(target) || math.IsInf(target, 0) || target <= 0 || target >= 1 || w.Total == 0 || w.Bad > w.Total { return 0, errors.New(\"invalid or missing evidence\") }\n return (float64(w.Bad) / float64(w.Total)) / (1 - target), nil\n}\nfunc page(long, short Window, target, threshold float64) (bool, error) {\n if math.IsNaN(threshold) || math.IsInf(threshold, 0) || threshold <= 0 { return false, errors.New(\"invalid threshold\") }\n a, err := burn(long, target); if err != nil { return false, err }\n b, err := burn(short, target); if err != nil { return false, err }\n return a >= threshold && b >= threshold, nil\n}\nfunc main() {\n high := Window{Total: 10000, Bad: 200}\n rate, _ := burn(high, 0.999)\n alert, _ := page(high, high, 0.999, 14.4)\n recovered, _ := page(high, Window{Total: 1000}, 0.999, 14.4)\n _, missing := burn(Window{}, 0.999)\n fmt.Printf(\"burn %.1fx page %t recovered %t missing %t\\n\", rate, alert, recovered, missing != nil)\n}\n","language":"go","title":"Calculate burn in a bounded model","walkthrough":"Expected output: burn 20.0x page true recovered false missing true. Both window samples are explicit input data; they are not collected automatically from a real monitoring system. Use tolerances when asserting floating-point rates."},{"body":"A long window captures significant consumption, while a short window confirms the problem is still active. Windows, thresholds and minimum event volume depend on the service and response time; a low-traffic service may need additional signals and careful sampling. Write down who receives the alert, the symptom, evidence links and a first safe action. Separate an urgent user-impacting page from a capacity-planning ticket.","title":"Combine time windows with a response contract"},{"body":"For a Go HTTP service, count eligible outcomes and record latency with stable operation labels. Avoid user IDs, raw URLs, request bodies, secrets and unbounded error strings as metric labels. Correlate structured logs and traces without treating either as a substitute for an aggregate SLI. A per-instance health probe answers a routing/process question; it is not automatically the service-level user outcome.","title":"Keep telemetry bounded and useful"},{"body":"Feed a sustained high-error sample, a brief spike, a recovered short window, zero observations and impossible counters into the model. Verify that missing evidence is visibly unavailable. Explain why each scenario pages or does not. Add a small load test in a disposable native service, observe the real route and compare client timeouts with server outcomes. Preserve the incident timeline and tune the policy from those observations, rather than muting unexplained alerts.","title":"Rehearse one page and one recovery"}],"takeaway":"Define eligible events, compute error-budget burn and require both recent and sustained evidence before paging.","title":"Use an SLO to decide when an incident needs attention","unitID":"devops","wrongAnswers":["CPU usage divided by the number of Pods","The error count without an eligible-event denominator"]},{"conceptTag":"devops.incident-recovery","designGuide":{"cautions":["Rehearse restoration in isolation and preserve/reconcile later accepted writes. Binary compatibility, persistent-data recovery and route verification are separate obligations."],"cost":"Automation needs explicit ownership, bounded privileges, tests and recovery evidence; a shorter command is not sufficient.","family":"Go for DevOps and reliability","flow":["Establish impact and owner","Collect bounded evidence","Choose a recoverable mitigation","Verify and improve the runbook"],"ratings":[],"strengths":["Use a bounded runbook to gather evidence, choose a reversible mitigation and distinguish binary rollback from restoring persistent data.","Make changes reviewable and verify the result against the original contract."]},"hint":"Track the writer boundary and where later acknowledged work lives.","id":"devops.incident-recovery","introduction":"An incident begins with user impact and uncertainty. A useful responder establishes scope, a current owner and an evidence timeline before trying unrelated commands. Recovery must preserve work the service already acknowledged, including writes accepted after a backup or a server move.","nuance":"Rehearse restoration in isolation and preserve/reconcile later accepted writes. Binary compatibility, persistent-data recovery and route verification are separate obligations.","objective":"Use a bounded runbook to gather evidence, choose a reversible mitigation and distinguish binary rollback from restoring persistent data.","question":"An old backup predates accepted writes. What makes a restore plan reviewable?","references":["https://sre.google/workbook/incident-response/","https://sre.google/sre-book/postmortem-culture/","https://kubernetes.io/docs/concepts/workloads/controllers/deployment/#rolling-back-a-deployment","https://www.postgresql.org/docs/current/continuous-archiving.html"],"reviewAnswer":"Preserve accepted writes before restoring state","reviewPrompt":"Rollback and persistent data","sections":[{"body":"Confirm the environment, service, affected operation and time window. Inspect the actual serving image, route, process health, recent release and user-outcome telemetry. For Kubernetes, verify context/namespace before logs or rollout inspection; for a Linux service, verify the named unit and journal window. Record facts separately from hypotheses. Keep access credentials and customer payloads out of shared incident notes.","title":"Start with read-only evidence and an explicit target"},{"body":"A mitigation may reduce traffic, disable a failing optional feature or restore a compatible binary. Name the person controlling the change, the exact target and version, the expected result, a deadline and the point at which to stop or reverse. Preserve original evidence while limiting ongoing impact. Communicate the observed effect rather than declaring recovery because a command exited zero. Concurrent responders should avoid silently changing the same resource.","title":"Select a mitigation with an owner and stop condition"},{"body":"The program returns a reviewable recommendation and performs no rollback or restore. An old binary is a candidate only when its declared reader range includes the current schema. If a restore would erase later acknowledged writes, recovering into a separate environment and reconciling those writes must be considered. The model intentionally has no “overwrite live data now” action.","code":"package main\n\nimport \"fmt\"\n\ntype Incident struct { CurrentSchema, OldReaderMin, OldReaderMax int; WritesSinceBackup bool }\nfunc recoveryPlan(i Incident) string {\n if i.CurrentSchema < 1 || i.OldReaderMin < 1 || i.OldReaderMin > i.OldReaderMax { return \"reject invalid compatibility evidence\" }\n if i.CurrentSchema >= i.OldReaderMin && i.CurrentSchema <= i.OldReaderMax { return \"candidate: roll back binary; verify route and outcomes\" }\n if i.WritesSinceBackup { return \"roll forward or restore separately and reconcile accepted writes\" }\n return \"rehearse isolated restore; do not overwrite the live writer\"\n}\nfunc main() {\n fmt.Println(recoveryPlan(Incident{CurrentSchema: 2, OldReaderMin: 1, OldReaderMax: 2}))\n fmt.Println(recoveryPlan(Incident{CurrentSchema: 2, OldReaderMin: 1, OldReaderMax: 1, WritesSinceBackup: true}))\n fmt.Println(recoveryPlan(Incident{CurrentSchema: 2, OldReaderMin: 1, OldReaderMax: 1}))\n}\n","language":"go","title":"A recovery decision model","walkthrough":"Expected lines: candidate: roll back binary; verify route and outcomes; roll forward or restore separately and reconcile accepted writes; rehearse isolated restore; do not overwrite the live writer. Compatibility metadata itself needs tests against real schemas, not optimistic labels."},{"body":"A completed backup job does not prove a usable restore. In an isolated environment, restore a known snapshot, verify integrity and application reads, document required configuration/key references and measure recovery time. State the accepted data-loss window and the source of truth for later writes. A container image rollback does not restore a database, and copying files while a writer is active is not automatically a consistent backup. Use the storage engine’s documented recovery method.","title":"Rehearse backup restoration before an emergency"},{"body":"Verify the user operation through the real route and observe the recovery window. Record the impact, detection gap, sequence of actions, contributing conditions and evidence for recovery. Add an independently testable action with an owner and due criterion: a missing compatibility test, a clearer runbook or a safer rollout gate. Keep the record focused on system behavior and learning. The goal is to reduce the chance and cost of repetition, not to identify a person to blame.","title":"Close the loop with a blameless improvement"}],"takeaway":"Use a bounded runbook to gather evidence, choose a reversible mitigation and distinguish binary rollback from restoring persistent data.","title":"Respond to an incident without destroying the accepted writes","unitID":"devops","wrongAnswers":["Overwrite the live volume and assume the writes can be retried","Treat an image rollback as a complete database recovery"]},{"conceptTag":"devops.iam-boundaries","designGuide":{"cautions":["An identity can authenticate successfully and still be denied a resource action. Test that denial deliberately."],"cost":"Real provider and network evidence requires an owned disposable environment; local files describe a contract without performing the integration.","family":"Go for DevOps and reliability","flow":["Identify principal and target","Constrain trust claims","Limit actions and lifetime","Test allowed and denied actions"],"ratings":[],"strengths":["Separate authentication, authorization and credential lifetime in a delivery workflow.","Keep an explicit contract and retain both successful and denied observations."]},"hint":"Separate who may assume the role from what the role may do.","id":"devops.iam-boundaries","introduction":"A green build does not authorize a deployment. Each job needs an identity, a target and a bounded permission set. Keep production credentials out of source, course exports and lab files.","nuance":"An identity can authenticate successfully and still be denied a resource action. Test that denial deliberately.","objective":"Separate authentication, authorization and credential lifetime in a delivery workflow.","question":"What should constrain a workload identity exchange?","references":["https://docs.aws.amazon.com/IAM/latest/UserGuide/best-practices.html"],"reviewAnswer":"Issuer, audience, workload claims","reviewPrompt":"Workload trust","sections":[{"body":"Record the CI job identity, environment and intended action before choosing permissions. A pull request from a fork should not receive deployment rights. Separate artifact-read, staging-deploy and production-promote roles. Restrict both the allowed actions and resource scope; a role name alone does not establish the boundary.","title":"Identify the principal and target"},{"body":"A workload identity can exchange an identity token for a short-lived role session. Bind trust to the expected issuer, audience, repository and protected environment. Inspect the trust policy as well as the permission policy. Avoid storing a long-lived administrator key in a workflow variable. Rotation and expiration reduce exposure but do not replace authorization.","title":"Prefer a short-lived exchange"},{"body":"In an owned disposable account, verify that the staging role can inspect its own target and is denied production changes. Record the principal, resource, attempted action and redacted audit event. Never paste tokens into logs. The local shell deliberately has no cloud authentication or egress; write the expected access matrix here, then perform the integration test in your own isolated environment.","code":"principal          staging/read  staging/deploy  production/deploy\nci-verify          allow         deny            deny\nci-staging         allow         allow           deny\nci-production      allow         deny            allow after approval","language":"text","title":"Prove denial as well as success","walkthrough":"Read each row as a distinct principal, not as one shared token. Verification has no deployment rights. Staging can change only staging. The production row still requires a separately approved job and a matching trust policy; this matrix is a design artifact, not evidence that a cloud policy was installed."}],"takeaway":"An operational identity is a narrow authorization contract with a lifetime, not a reusable administrator secret.","title":"IAM: give a job one narrow, short-lived identity","unitID":"devops","wrongAnswers":["Only the friendly name of the deployment role.","A shared administrator key committed with the pipeline."]},{"conceptTag":"devops.iac-state","designGuide":{"cautions":["Locking coordinates cooperating writers; it does not prove that an apply is safe or that external drift cannot happen."],"cost":"Real provider and network evidence requires an owned disposable environment; local files describe a contract without performing the integration.","family":"Go for DevOps and reliability","flow":["Confirm backend and account","Observe state and provider","Review and lock one writer","Inspect outcome and re-plan"],"ratings":[],"strengths":["Explain state ownership, review a proposed change and recover from a failed apply without discarding evidence.","Keep an explicit contract and retain both successful and denied observations."]},"hint":"Retain the record that connects intent to real objects.","id":"devops.iac-state","introduction":"Declarative infrastructure tools compare configuration, recorded state and an observed provider view. A plan is a proposal at an observation boundary; it is not a guarantee that the world stays unchanged until apply.","nuance":"Locking coordinates cooperating writers; it does not prove that an apply is safe or that external drift cannot happen.","objective":"Explain state ownership, review a proposed change and recover from a failed apply without discarding evidence.","question":"What should follow a partial apply failure?","references":["https://developer.hashicorp.com/terraform/language/state/locking","https://developer.hashicorp.com/terraform/cli/commands/plan"],"reviewAnswer":"Inspect state and resources; re-plan","reviewPrompt":"Partial IaC apply","sections":[{"body":"Configuration describes intent; state binds configured resources to provider objects; a refresh observes the current remote system. Drift is an out-of-band change, not necessarily permission to overwrite it. Before an apply, identify the workspace, backend, account and region. A correct plan against the wrong account is still a dangerous change.","title":"Separate the three views"},{"body":"Use a backend with appropriate state locking and access control, keep state and plan files out of public repositories, and serialize writers. State can contain sensitive values. Do not remove a lock simply because another job is slow: establish ownership and whether the operation is still running. A forced unlock or manual state edit requires a recovery procedure and evidence.","title":"Preserve state ownership"},{"body":"Review create/update/destroy actions and blast radius before an explicit apply in a disposable environment. After a partial failure, inspect both provider reality and state, re-plan and resolve the cause. Do not delete state to make a red error disappear. Restore and import are operations with identity and backup requirements, not generic undo commands. The app provides no provider executables or remote backend; the exercise here is a reviewable plan and access checklist, followed by a real rehearsal in your own environment.","code":"configuration: desired replicas = 3\nstate:         service id = svc-42, last replicas = 2\nprovider:      svc-42 currently has 1 replica\nplan:          update svc-42 to 3, destroy 0\napply:         requires owned lock and explicit approval","language":"text","title":"Verify outcomes and recovery","walkthrough":"The service identity binds state to one real resource. Refresh discovers a count of one; configuration still requests three. Review the update against that observation and the selected account before applying. If an apply fails, preserve both the state and provider evidence, then make a fresh plan instead of assuming every action was rolled back."}],"takeaway":"Treat infrastructure state as sensitive operational evidence with one accountable writer.","title":"Infrastructure as code: plan, lock and inspect drift","unitID":"devops","wrongAnswers":["Delete the state file and recreate every object.","Force-unlock immediately without checking the current writer."]},{"conceptTag":"devops.network-evidence","designGuide":{"cautions":["Repeatedly testing from a different environment can hide the original failure. Preserve the caller and verify the failing boundary."],"cost":"Real provider and network evidence requires an owned disposable environment; local files describe a contract without performing the integration.","family":"Go for DevOps and reliability","flow":["Record caller and request","Resolve name and connect","Verify TLS peer identity","Check HTTP and repeat failure"],"ratings":[],"strengths":["Collect evidence at the failing boundary without disabling peer verification.","Keep an explicit contract and retain both successful and denied observations."]},"hint":"Separate name resolution from the connection and application contract.","id":"devops.network-evidence","introduction":"A request can fail before an HTTP handler runs. Start from the exact caller, hostname, port and scheme, then locate the first failing boundary: name resolution, connection, TLS identity or application contract.","nuance":"Repeatedly testing from a different environment can hide the original failure. Preserve the caller and verify the failing boundary.","objective":"Collect evidence at the failing boundary without disabling peer verification.","question":"What does a successful DNS lookup prove?","references":["https://kubernetes.io/docs/tasks/administer-cluster/dns-debugging-resolution/"],"reviewAnswer":"Name resolution for that caller","reviewPrompt":"DNS success proves","sections":[{"body":"DNS results and routing depend on the actual environment. A successful lookup on a laptop does not establish what a pod resolves. Identify the namespace, search domains, service name, endpoint addresses and caller network policy. Record timestamps and the failing request before changing configuration.","title":"Keep the caller in the experiment"},{"body":"An address resolving is not proof that the port accepts connections. A connected socket is not proof of the TLS peer name or trusted chain. A TLS handshake is not proof that a route returns the expected version. Use explicit deadlines and correlate a request ID with server evidence. Disabling certificate validation hides the trust failure instead of diagnosing it.","title":"Separate layers and preserve identity"},{"body":"Write down the expected name, scheme, port, peer identity and HTTP status/body. Change one boundary at a time in an owned disposable environment, re-run the same request, and retain negative cases. Local shell files can model a contract and log analysis, but do not generate DNS, TLS or cluster evidence. The app has no guest sockets, curl, SSH or kubectl; use an isolated native environment for those integration checks.","code":"caller: orders-pod, namespace shop\nname:   payments.shop.svc.cluster.local\nDNS:    returned 10.0.0.12\nTCP:    port 443 accepted\nTLS:    peer hostname mismatch\nHTTP:   not reached","language":"text","title":"Turn the finding into a regression check","walkthrough":"The DNS and TCP observations establish only their own boundaries from the named caller. A TLS hostname mismatch prevents a trusted HTTP request, so no HTTP health conclusion follows. Keep verification enabled, inspect the requested hostname and certificate identity, correct the contract, and repeat the request from the same caller."}],"takeaway":"A useful incident note identifies the first failed boundary and proves recovery from the same caller.","title":"Diagnose a service boundary: DNS, transport, TLS and HTTP","unitID":"devops","wrongAnswers":["That the TLS peer identity is trusted and matches the hostname.","That the application route is healthy and returns the intended version."]}],"revision":"2026-11-07.1","schemaVersion":1,"solutions":{},"units":[{"id":"operations","lessons":[{"conceptTags":["tooling.bash"],"explanation":"A shell starts in a working directory, and relative paths are resolved there. Before building or moving files, establish that location. These exercises use a new scratch directory on your own Mac or Linux machine; no administrator permissions are needed.","id":"operations.shell-files","objective":"Use pwd, cd, ls, mkdir, cp and mv in a small disposable workspace.","task":{"reading":{}},"title":"Bash essentials: navigate, inspect and copy files"},{"conceptTags":["tooling.bash"],"explanation":"Most development investigations begin with a filename, a symbol or a short log fragment. Use small commands to narrow the evidence before opening a huge file. The examples assume you are in a trusted Go project and have a text application log named app.log.","id":"operations.shell-text","objective":"Combine find, grep, head, tail, sort and uniq without hiding their exit behavior.","task":{"reading":{}},"title":"Find code and inspect logs from the command line"},{"conceptTags":["tooling.bash"],"explanation":"Bash is useful for connecting build and deployment tools on a developer machine. Go itself does not require Bash, Docker or Kubernetes. Learning their boundaries helps when a Go program becomes part of a service workflow; these commands are reading examples, not app terminal commands.","id":"operations.bash-arguments","objective":"Read a small build script without splitting paths or accidentally invoking a shell through Go.","task":{"reading":{}},"title":"Bash passes arguments; quoting defines their boundaries"},{"conceptTags":["tooling.bash"],"explanation":"A script is another program with success and failure paths. A command printing plausible output can still fail. Pipelines complicate this because the last command can succeed even when an earlier producer failed.","id":"operations.bash-failures","objective":"Read pipeline failure behavior and keep configuration and secrets out of command strings.","task":{"reading":{}},"title":"Pipelines, exit codes and explicit failure handling"},{"conceptTags":["tooling.bash"],"explanation":"A process has a PID, an exit status and open streams. Starting a service in the background does not detach it from responsibility: keep the PID and wait for completion. These commands assume a local Go project with cmd/api and an available port.","id":"operations.shell-processes","objective":"Start one Go service, retain its PID, send TERM and wait for its result.","task":{"reading":{}},"title":"Processes, signals and exit status"},{"conceptTags":["tooling.bash"],"explanation":"A useful script has explicit inputs and predictable cleanup. Bash distinguishes positional arguments, shell variables and exported environment. This lesson puts those pieces into a small test wrapper instead of assuming that adding set -e makes every failure path correct.","id":"operations.shell-scripts","objective":"Read required configuration, forward quoted arguments and clean a temporary workspace with a trap.","task":{"reading":{}},"title":"Small scripts: arguments, environment and cleanup"},{"conceptTags":["tooling.git"],"explanation":"Git records snapshots, not a magic backup of every unsaved editor buffer. Start in an existing local repository and inspect your changes. The sequence below makes a topic branch, stages one reviewed path and records a local commit; publishing comes in the next lesson.","id":"operations.git-local","objective":"Keep working tree, staging area and committed history distinct.","task":{"reading":{}},"title":"Git daily work: inspect, branch, stage and commit"},{"conceptTags":["tooling.git"],"explanation":"A remote-tracking branch is your local record of a remote branch at the last fetch. Fetching updates that record without integrating it into your current branch. The examples assume an origin remote, a main branch and an existing topic branch you own.","id":"operations.git-remotes","objective":"Inspect upstream changes before integration and keep unfinished work recoverable.","task":{"reading":{}},"title":"Git collaboration: fetch, compare, stash and push"},{"conceptTags":["tooling.go-tools"],"explanation":"A useful Go development loop checks the module boundary, formatting, tests, static diagnostics and the final build. These commands are for the native Go toolchain on a development machine; platform support and build tags can change which packages are selected.","id":"operations.go-tooling","objective":"Use the native Go CLI to inspect a module and check a service before packaging it.","task":{"reading":{}},"title":"Go toolbelt: modules, tests, vet and build"},{"conceptTags":["tooling.networking"],"explanation":"An API can fail before any handler runs, or return an HTTP error over a perfectly healthy connection. curl helps identify that boundary. These examples target your own local Go service at 127.0.0.1:8080 with a /healthz endpoint; adjust the paths to your application.","id":"operations.http-debugging","objective":"Probe a local API and separate DNS, connection, HTTP and application failures.","task":{"reading":{}},"title":"HTTP debugging: curl, status codes and time budgets"},{"conceptTags":["tooling.linux"],"explanation":"A native Go binary can run directly under a service manager; Kubernetes is not required. These examples assume Linux with systemd and a preinstalled go-api.service. They do not apply to macOS launchd or every container environment.","id":"operations.linux-service","objective":"Inspect a systemd service, follow its logs and understand its restart boundary.","task":{"reading":{}},"title":"A Go service on Linux: systemctl and journalctl"}],"summary":"Bash, Git, Go tools, HTTP debugging and Linux service commands.","title":"Around Go: command line","translationNote":"Read commands and manifests here; use your own development environment to run them. These tools are useful deployment options, not prerequisites for every Go program."},{"id":"containers","lessons":[{"conceptTags":["tooling.containers"],"explanation":"A container image packages a native application and its runtime files. It does not compile Go inside the iOS app, and it does not remove the need to maintain the operating environment. Multi-stage builds let the final image omit the compiler and source tree.","id":"operations.docker-build","objective":"Separate the build stage from the runtime image and identify what a minimal image leaves out.","task":{"reading":{}},"title":"Build a small Go image with explicit runtime needs"},{"conceptTags":["tooling.containers"],"explanation":"Start with a trusted project containing the Dockerfile from the earlier lesson and a Go service listening on :8080. The following commands use an isolated development container named go-api-dev; an image, a container instance and a published port are different objects.","id":"operations.docker-run","objective":"Run a named local container and diagnose it with logs, inspect and stats.","task":{"reading":{}},"title":"Docker daily commands: build, run, inspect and stop"},{"conceptTags":["tooling.containers"],"explanation":"Compose defines a local multi-container environment in one file. This example assumes your API reads REDIS_ADDR, listens on :8080 and tolerates transient downstream failures. Use a disposable directory for the exercise and save the file below as compose.yaml.","id":"operations.docker-compose","objective":"Read compose.yaml and use config, up, ps, logs, exec and down.","task":{"reading":{}},"title":"Compose: run an API and Redis as one local stack"},{"conceptTags":["tooling.containers"],"explanation":"A container writable layer usually disappears when its instance is removed. A bind mount maps a host path; a named volume has a lifecycle managed by the container runtime. These local examples use a dedicated fixture and Redis to demonstrate the difference.","id":"operations.docker-volumes","objective":"Choose a mount for configuration or persistent state and inspect it without deleting data.","task":{"reading":{}},"title":"Container storage: bind mounts, volumes and permissions"},{"conceptTags":["tooling.containers"],"explanation":"Docker and Podman can build and run OCI-style container images, but their host integration, daemon model, networking and rootless behavior are not identical. An image is an artifact; a container is a running or stopped instance with its own lifecycle.","id":"operations.podman-runtime","objective":"Distinguish image, container, host networking and persistent data while comparing local runtimes.","task":{"reading":{}},"title":"Docker and Podman: images are not running containers"},{"conceptTags":["tooling.containers"],"explanation":"A cluster pulls an image from a registry it can reach; a local Docker image does not appear there automatically. Tags are mutable names, while a digest identifies specific image content. Replace the example registry and owner with a namespace where you have permission to publish.","id":"operations.container-registry","objective":"Tag and push an image you own, inspect its digest and match its platform to the deployment.","task":{"reading":{}},"title":"Publish an image: tags, digests and target platforms"}],"summary":"Build, run, inspect and publish with Docker, Compose and Podman.","title":"Around Go: containers","translationNote":"Use your own development machine for these command examples. Each lesson distinguishes images, instances, networking and stored data."},{"id":"kubernetes","lessons":[{"conceptTags":["tooling.kubernetes"],"explanation":"kubectl reads a kubeconfig and sends requests to its selected cluster as a configured identity. A namespace narrows many workload operations but does not select a cluster. These lessons assume an existing disposable development cluster with a context named dev-cluster; substitute your actual development context.","id":"operations.kubernetes-contexts","objective":"Inspect the target cluster and explicitly scope commands before making changes.","task":{"reading":{}},"title":"kubectl first steps: context, namespace and permissions"},{"conceptTags":["tooling.kubernetes"],"explanation":"Kubernetes operates containerized workloads. It does not write your Go code or remove distributed-system failures. A Deployment describes the desired replicated workload; a Service gives selected Pods a stable network abstraction while individual Pods are replaced.","id":"operations.kubernetes-workloads","objective":"Read Deployment, Pod labels, resource budgets and a Service without confusing them with an application build.","task":{"reading":{}},"title":"Kubernetes reconciles a workload; a Service routes to it"},{"conceptTags":["tooling.kubernetes"],"explanation":"A manifest declares desired state; the API accepting it is only the start of reconciliation. Save the earlier Deployment and Service example as deployment.yaml, set a real pullable image reference and use the go-lab development namespace from the context lesson.","id":"operations.kubernetes-apply","objective":"Validate a workload document and observe reconciliation rather than assuming apply means ready.","task":{"reading":{}},"title":"Deploy a manifest: explain, dry-run, diff and apply"},{"conceptTags":["tooling.kubernetes"],"explanation":"Read the workload state before changing it. A Deployment, a Pod and a container can each have a different status, so diagnose the layer that is failing. These commands refer to the earlier go-api Deployment in the explicit go-lab development namespace.","id":"operations.kubernetes-inspect","objective":"Find the concrete reason behind Pending, CrashLoopBackOff or an unready container.","task":{"reading":{}},"title":"Debug Pods: get, describe, logs, events and top"},{"conceptTags":["tooling.kubernetes"],"explanation":"A Service object can exist while routing to no useful Pods. Diagnose its selector, selected endpoints, target port and application listener separately. This lesson uses the earlier internal Service go-api on port 80 targeting the Go container port 8080.","id":"operations.kubernetes-network","objective":"Trace a request from a local port through a Service to a ready application endpoint.","task":{"reading":{}},"title":"Service routing: selectors, endpoints and port-forward"},{"conceptTags":["tooling.kubernetes"],"explanation":"Separate application configuration from the image artifact. ConfigMaps hold ordinary configuration; Secrets are intended for sensitive values but are not made confidential merely by base64 encoding. These development examples assume a namespace you own and the permissions to manage its configuration.","id":"operations.kubernetes-config","objective":"Create a non-secret setting, mount a Secret reference and understand why environment changes need replacement.","task":{"reading":{}},"title":"Configuration: ConfigMaps, Secrets and update behavior"},{"conceptTags":["tooling.kubernetes"],"explanation":"A process being alive does not mean it can accept useful work. Readiness controls whether a Pod receives normal Service traffic. Liveness can trigger a restart. A startup probe can allow initialization before the other probes take effect. Choose each signal according to the failure it should detect.","id":"operations.probes-and-shutdown","objective":"Give each health signal one purpose and arrange a bounded stop that drains owned work.","task":{"reading":{}},"title":"Readiness, liveness and graceful shutdown"},{"conceptTags":["tooling.kubernetes"],"explanation":"A Deployment rollout changes its Pod template and replaces replicas under its update policy. A timeout or unhealthy Pod requires investigation before further mutations. These examples operate only on the inspected development go-api Deployment, using a real tested image reference in place of the placeholder.","id":"operations.kubernetes-rollout","objective":"Change an image deliberately, observe revisions and understand what rollback cannot restore.","task":{"reading":{}},"title":"Release operations: rollout, scale and rollback"}],"summary":"Contexts, deployments, logs, services, configuration, probes and rollbacks.","title":"Around Go: Kubernetes","translationNote":"Start with the context lesson and a disposable development cluster. Examples keep cluster and namespace explicit; replace placeholder names and images before use."},{"id":"devops","lessons":[{"conceptTags":["devops.delivery-loop"],"explanation":"A DevOps engineer helps teams deliver and operate changes reliably. Go is useful for portable command-line tools, controllers, exporters and services. The work also involves Linux, networking, release ownership, incident response and collaboration. Start with one service and a repeatable feedback loop rather than collecting tool names.","id":"devops.delivery-loop","objective":"Connect a service change to tests, delivery, operation and feedback, and choose a small automation project with a measurable outcome.","task":{"reading":{}},"title":"DevOps is a delivery feedback loop; Go builds its tools"},{"conceptTags":["devops.safe-cli"],"explanation":"A script becomes infrastructure when other programs rely on it. Define its input, output, exit codes and side effects before adding concurrency or cloud APIs. A read-only inventory tool is a useful first project because failure can be tested without changing a real system.","id":"devops.safe-cli","objective":"Design a Go command with bounded input, machine-readable output, explicit exit status and cancellation ownership.","task":{"reading":{}},"title":"Build a small operational CLI with explicit boundaries"},{"conceptTags":["devops.reconciliation"],"explanation":"A controller repeatedly compares desired state with observed state. Network retries and concurrent operators make “run this command once” an unreliable model. A useful plan says exactly what will change, from which observed version, and what evidence will establish convergence.","id":"devops.reconciliation","objective":"Separate observation, planning and application; use a version precondition and make a repeated successful reconciliation converge.","task":{"reading":{}},"title":"Reconcile desired state without overwriting a newer observation"},{"conceptTags":["devops.delivery-artifacts"],"explanation":"A source commit, mutable image tag and built binary are different identities. A pipeline can test one artifact and accidentally deploy another. Make every promotion name the exact digest already verified, and keep the build environment and target architecture visible.","id":"devops.delivery-artifacts","objective":"Bind verification evidence and release approval to an immutable artifact, then distinguish application rollout from data recovery.","task":{"reading":{}},"title":"CI/CD: build once, verify the digest, promote the same artifact"},{"conceptTags":["devops.slo-burn"],"explanation":"An SLI measures a user-relevant outcome; an SLO defines the intended level over a stated window. Error-budget burn relates the observed bad-event fraction to the allowed fraction. It can connect delivery decisions to reliability evidence more usefully than paging on every CPU spike.","id":"devops.slo-burn","objective":"Define eligible events, compute error-budget burn and require both recent and sustained evidence before paging.","task":{"reading":{}},"title":"Use an SLO to decide when an incident needs attention"},{"conceptTags":["devops.incident-recovery"],"explanation":"An incident begins with user impact and uncertainty. A useful responder establishes scope, a current owner and an evidence timeline before trying unrelated commands. Recovery must preserve work the service already acknowledged, including writes accepted after a backup or a server move.","id":"devops.incident-recovery","objective":"Use a bounded runbook to gather evidence, choose a reversible mitigation and distinguish binary rollback from restoring persistent data.","task":{"reading":{}},"title":"Respond to an incident without destroying the accepted writes"},{"conceptTags":["devops.iam-boundaries"],"explanation":"A green build does not authorize a deployment. Each job needs an identity, a target and a bounded permission set. Keep production credentials out of source, course exports and lab files.","id":"devops.iam-boundaries","objective":"Separate authentication, authorization and credential lifetime in a delivery workflow.","task":{"reading":{}},"title":"IAM: give a job one narrow, short-lived identity"},{"conceptTags":["devops.iac-state"],"explanation":"Declarative infrastructure tools compare configuration, recorded state and an observed provider view. A plan is a proposal at an observation boundary; it is not a guarantee that the world stays unchanged until apply.","id":"devops.iac-state","objective":"Explain state ownership, review a proposed change and recover from a failed apply without discarding evidence.","task":{"reading":{}},"title":"Infrastructure as code: plan, lock and inspect drift"},{"conceptTags":["devops.network-evidence"],"explanation":"A request can fail before an HTTP handler runs. Start from the exact caller, hostname, port and scheme, then locate the first failing boundary: name resolution, connection, TLS identity or application contract.","id":"devops.network-evidence","objective":"Collect evidence at the failing boundary without disabling peer verification.","task":{"reading":{}},"title":"Diagnose a service boundary: DNS, transport, TLS and HTTP"}],"summary":"Operational CLIs, reconciliation, verified delivery, SLOs, incidents and data-safe recovery.","title":"Around Go: DevOps and reliability","translationNote":"Begin with command line, containers and Kubernetes. Go models run locally; real infrastructure, process and monitoring exercises need your own disposable native environment."}]}