Skip to content
Hands-on IT IT Drills

Day 14: Projects and platform ergonomics

Goal: Every project brings its own environment, language versions and commands, and a prod cluster is impossible to overlook in the terminal. · Duration: approx. 120 min · Prerequisite: Day 13

Briefing

  • direnv loads variables from .envrc when you cd into the project and unloads them when you leave. mise provides the right Go, Python and Node versions per project.
  • make or just are a project’s table of contents: make help instead of searching the wiki.
  • Kubernetes: a kubeconfig per project, kubectx/kubens, aliases with completion, a guard for prod and a red prompt.
  • Scripts run with set -euo pipefail, trap and shellcheck. entr, watch and hyperfine close the feedback loop.
  • Everything runs in ~/term-lab/projekt and with a lab kubeconfig with made-up contexts. Your real ~/.kube/config stays untouched.
cd ~/term-lab/projekt
  ├─ direnv ─► APP_ENV, PORT, KUBECONFIG=../kube/config, PATH+=scripts
  ├─ mise   ─► go 1.25, python 3.13, node 22
  └─ make   ─► run · test · vet · lint · report

Drill 1: direnv – environment per directory

The hook goes into the lab configuration; then restart the shell.

echo 'eval "$(direnv hook zsh)"' > ~/term-lab/config/zsh/direnv.zsh
exec zsh
cd ~/term-lab/projekt
cat > .envrc <<'EOF'
# Project environment – loaded on entering, unloaded on leaving
export APP_ENV=dev
export PORT=8080
export KUBECONFIG="$(expand_path ../kube/config)"
export K9S_CONFIG_DIR="$(expand_path ../kube/k9s)"
PATH_add scripts
dotenv_if_exists .env.local
EOF
echo 'DB_PASSWORD=lab-db-pw-1234   # Lab-Wert' > .env.local
echo '.env.local' >> .gitignore

Expected:

direnv: error ~/term-lab/projekt/.envrc is blocked. Run `direnv allow` to approve
its content

Why? direnv only runs files you’ve approved. Every change to .envrc blocks it again – that way a foreign git pull can’t slip anything past you.

direnv allow
echo "$APP_ENV $PORT $DB_PASSWORD"; echo $KUBECONFIG
cd .. && echo "draußen: ${APP_ENV:-leer}"; cd projekt

Expected:

direnv: loading ~/term-lab/projekt/.envrc
direnv: export +APP_ENV +DB_PASSWORD +K9S_CONFIG_DIR +KUBECONFIG +PORT ~PATH
dev 8080 lab-db-pw-1234
/Users/<du>/term-lab/kube/config
direnv: unloading
draußen: leer
direnv: loading ~/term-lab/projekt/.envrc

Security: .envrc goes into the repo, .env.local with secrets never does. Even better: fetch secrets at runtime, e.g. export TOKEN=$(op read op://Lab/api/token) in the .envrc.

Save your progress? Sign up for free

Drill 2: mise – language versions per project

mise use writes a mise.toml into the project and downloads the tools (about 150 MB in total, to ~/.local/share/mise). In the lab, redirect that beforehand with export MISE_DATA_DIR=$LAB/mise; then your real mise directory stays untouched. -n shows beforehand what would happen.

echo 'eval "$(mise activate zsh)"' > ~/term-lab/config/zsh/mise.zsh
exec zsh
cd ~/term-lab/projekt
mise use -n [email protected] [email protected] node@22
mise use [email protected] [email protected] node@22
cat mise.toml

Expected (shortened, patch versions may differ):

mise [email protected]    ⇢ would install
mise [email protected] ⇢ would install
mise [email protected]  ⇢ would install
mise would update ~/term-lab/projekt/mise.toml (add: [email protected], [email protected], …)
mise ✓ [email protected]  10.7s  node-v22.23.3-darwin-arm64.tar.gz
mise ✓ [email protected]      17.5s  go1.25.14.darwin-arm64.tar.gz
mise ~/term-lab/projekt/mise.toml tools: [email protected], [email protected], [email protected]
[tools]
go = "1.25"
node = "22"
python = "3.13"
mise current
whence -p go python3 node | sed "s#$HOME#~#"

Expected:

go 1.25.14
node 22.23.3
python 3.13.16
~/.local/share/mise/installs/go/1.25.14/bin/go
~/.local/share/mise/installs/python/3.13/bin/python3
~/.local/share/mise/installs/node/22/bin/node

Warning: Check in the would update line which file mise use changes. If it shows your global ~/.config/mise/config.toml, force the project file with mise use --path mise.toml ….

Why mise instead of brew install go? Brew knows one version for all projects. With mise, every repo has its own, recorded in mise.toml and checked in – CI reads the same file.

Save your progress? Sign up for free

Drill 3: Safe scripts – set -euo pipefail, trap, shellcheck

First the counterexample. Seven lines, four real dangers:

cd ~/term-lab/projekt
cat > ~/term-lab/unsicher.sh <<'EOF'
#!/bin/bash
cd $1
for f in $(ls *.log); do
  grep ERROR $f | wc -l
done
rm -rf $BUILD_DIR/*
EOF
shellcheck ~/term-lab/unsicher.sh | grep '\^.*SC' | cut -c1-80

Expected (shortened):

^---^ SC2164 (warning): Use 'cd ... || exit' or 'cd ... || return' in case cd fa
   ^-- SC2086 (info): Double quote to prevent globbing and word splitting.
         ^---------^ SC2045 (error): Iterating over ls output is fragile. Use gl
  ^-----------^ SC2126 (style): Consider using 'grep -c' instead of 'grep|wc -l'
       ^----------^ SC2115 (warning): Use "${var:?}" to ensure this never expand

Why is SC2115 the most important line? If BUILD_DIR is empty, it reads rm -rf /*. That happens when cd fails and nobody notices.

Three options catch exactly these errors:

bash -c 'set -u; echo "Ziel: $BUILD_DIR"; echo weiter'; echo "rc=$?"
bash -c 'grep x /nix/da | sort; echo "rc=$?"'
bash -c 'set -o pipefail; grep x /nix/da | sort; echo "rc=$?"'

Expected:

bash: Zeile 1: BUILD_DIR ist nicht gesetzt.
rc=127
grep: /nix/da: No such file or directory
rc=0
grep: /nix/da: No such file or directory
rc=2

-e aborts on the first error, -u on unknown variables, pipefail makes an error in the middle of a pipe visible. Now the template for all your own scripts:

cat > scripts/fehler.sh <<'EOF'
#!/usr/bin/env bash
# fehler.sh – count ERROR lines per component
# Usage: scripts/fehler.sh [logfile]
set -euo pipefail
IFS=$'\n\t'

readonly LOG="${1:-logs/app.log}"
tmp="$(mktemp -t fehler.XXXXXX)"
cleanup() { rm -f -- "$tmp"; }
trap cleanup EXIT
trap 'echo "✘ Fehler in Zeile $LINENO: $BASH_COMMAND" >&2' ERR

[[ -r "$LOG" ]] || { echo "✘ Datei nicht lesbar: $LOG" >&2; exit 2; }

grep -F ' ERROR ' -- "$LOG" > "$tmp" || true    # 0 matches is not an error
awk '{print $2}' "$tmp" | sort | uniq -c | sort -rn
echo "Summe: $(wc -l < "$tmp" | tr -d ' ')"
EOF
chmod +x scripts/fehler.sh
shellcheck scripts/fehler.sh && echo "✔ shellcheck"
fehler.sh; fehler.sh nix.log; echo "rc=$?"

Expected:

✔ shellcheck
  50 checkout
Summe: 50
✘ Datei nicht lesbar: nix.log
rc=2

Why does fehler.sh work without a path? PATH_add scripts from the .envrc. The EXIT trap cleans up the temp file even on abort and Ctrl-C.

Save your progress? Sign up for free

Drill 4: make and just – the project’s table of contents

A help target reads the ## comments from the Makefile itself. Make needs tabs before the commands – so copy the file from the companion material.

cp $BUCH/projekt-tools/Makefile ~/term-lab/projekt/
make
make report
make test vet lint

Expected:

  help     Diese Hilfe
  run      Shop lokal starten (PORT aus .envrc)
  test     Go-Tests
  vet      Go statisch prüfen
  lint     Shell-Skripte prüfen
  report   Log-Level zählen
python3 scripts/report.py logs/app.log
INFO   350
WARN   50
ERROR  50
DEBUG  50
go test ./...
?       example.com/shop/cmd/shop   [no test files]
?       example.com/shop/internal/cart  [no test files]
go vet ./...
shellcheck scripts/*.sh

just is a pure command runner without make’s legacy: no tabs, parameters with default values, just --list built in. The file $BUCH/projekt-tools/justfile contains the same targets.

cp $BUCH/projekt-tools/justfile ~/term-lab/projekt/
just --list
just report logs/app.log

Expected (shortened, may differ depending on version):

Available recipes:
    check-manifests ctx="kind-lab" # Manifeste gegen einen Kontext prüfen …
    default                        # Standard: Rezepte auflisten
    lint                           # Shell-Skripte prüfen
    report file="logs/app.log"     # Log-Level zählen, optional andere Datei
    run                            # Shop lokal starten
    test                           # Go-Tests
INFO   350
…

Tip: Make if the team already has it or if real file dependencies matter. just if it’s only about named commands. mise can do the same with [tasks] in mise.toml – one tool fewer.

Save your progress? Sign up for free

Drill 5: Lab kubeconfig, kubectx and kubens

The .envrc already points to ~/term-lab/kube/config. The script creates three made-up contexts there – without a real cluster and without your real kubeconfig. Every call in it carries kubectl config --kubeconfig "$KC" … – that’s the insurance.

$BUCH/projekt-tools/kubeconfig-lab.sh ~/term-lab/kube/config
cd ~/term-lab/projekt          # direnv sets KUBECONFIG
kubectl config get-contexts

Expected:

Switched to context "kind-lab".
CURRENT   NAME         CLUSTER      AUTHINFO          NAMESPACE
*         kind-lab     kind-lab     kind-lab-user     default
          kunde-dev    kunde-dev    kunde-dev-user    default
          kunde-prod   kunde-prod   kunde-prod-user   default

Now switch. kubectx works purely locally in the kubeconfig; - jumps back like cd -.

kubectx
kubectx kunde-dev
kubectx -
kubectx -c

Expected:

kind-lab
kunde-dev
kunde-prod
✔ Switched to context "kunde-dev".
✔ Switched to context "kind-lab".
kind-lab

kubens asks the API server for the namespaces – without a cluster it fails. But the namespace can also be set offline on the context:

kubens shop
kubectl config set-context --current --namespace=shop
kubectl config view --minify -o jsonpath='{..namespace}'; echo

Expected:

error: failed to query if namespace exists (is cluster accessible?): …
dial tcp 127.0.0.1:6443: connect: connection refused
Context "kind-lab" modified.
shop

Tip: Without an argument and with fzf installed, kubectx and kubens open a fuzzy picker (Day 7). kubectx remembers the previous context in ~/.kube/kubectx – the only file it writes outside the kubeconfig.

Save your progress? Sign up for free

Drill 6: kubectl aliases, completion and a prod guard

$BUCH/projekt-tools/k8s.zsh brings aliases, completion for k and a kubectl function that only lets write commands on *prod* through after confirmation. Completion needs compinit from Day 2.

cp $BUCH/projekt-tools/k8s.zsh ~/term-lab/config/zsh/
exec zsh
echo "Completion für k: $_comps[k]"
alias k kgp

Expected:

Completion für k: _kubectl
k=kubectl
kgp='kubectl get pods'

The guard at its core:

kubectl() {
  local ctx verb="${1:-}"
  ctx=$(command kubectl config current-context 2>/dev/null)
  if [[ $ctx == *prod* && $verb == (apply|create|delete|edit|patch|replace\
|scale|rollout|drain|cordon|label|annotate|set) ]]; then
    print -P "%F{red}%BACHTUNG:%b kubectl $verb auf Kontext '$ctx'%f"
    read -q "?Wirklich ausführen? [y/N] " || { echo; return 1; }
    echo
  fi
  command kubectl "$@"
}

Try it out – type n:

kubectx kunde-prod
k delete pod web-1; echo "rc=$?"
k get pods --request-timeout=2s
kubectx kind-lab

Expected:

✔ Switched to context "kunde-prod".
ACHTUNG: kubectl delete auf Kontext 'kunde-prod'
Wirklich ausführen? [y/N] n
rc=1
Unable to connect to the server: dial tcp: lookup prod.k8s.kunde.example: no such host
✔ Switched to context "kind-lab".

Why command kubectl? Without command, the function calls itself. Read commands like get go through without confirmation.

Alias Command Mnemonic
k kubectl everything starts with k
kgp / kgpa get pods / -A get pods all
kd / kl describe / logs -f describe, logs
kx / kn kubectx / kubens context, namespace

Tip: source <(kubectl completion zsh) costs about 25 ms on every shell start (Drill 9 measures it). Faster: run kubectl completion zsh > ~/term-lab/zsh/completions/_kubectl once and add the directory to fpath before compinit.

Save your progress? Sign up for free

Drill 7: Prod in red – the prompt

starship has a kubernetes module that’s off by default. Patterns per context color prod red and shorten long names. Append the config to the lab starship.toml (STARSHIP_CONFIG from Day 0) – check beforehand that there’s no [kubernetes] block in it yet.

grep -q '^\[kubernetes\]' ~/term-lab/config/starship.toml || \
cat >> ~/term-lab/config/starship.toml <<'EOF'

[kubernetes]
disabled = false
format = '[$symbol$context( \($namespace\))]($style) '
style = 'yellow'

[[kubernetes.contexts]]
context_pattern = '.*prod.*'
style = 'bold white bg:red'
context_alias = 'PROD'

[[kubernetes.contexts]]
context_pattern = 'kind-(?P<name>.+)'
style = 'green'
context_alias = 'kind:$name'
EOF
starship module kubernetes; echo
kubectx kunde-prod >/dev/null; starship module kubernetes; echo; kubectx - >/dev/null

Expected (shortened, may differ depending on version; colors not visible here):

☸ kind:lab (shop)
☸ PROD (default)

Without starship, k8s_prompt from k8s.zsh takes over the right prompt (RPROMPT): yellow for everything, red and bold for *prod*. It only reads the kubeconfig, without an API call.

print -P "$(k8s_prompt)"
kubectx kunde-prod >/dev/null; print -P "$(k8s_prompt)"; kubectx - >/dev/null

Expected (top yellow, bottom red):

⎈ kind-lab:shop
⎈ kunde-prod:default

Warning: A prompt shows the context at the time it’s drawn. If another terminal switches the context in the same kubeconfig, the display is wrong until the next line. Hence: one kubeconfig per project via direnv instead of a global one.

Save your progress? Sign up for free

Drill 8: k9s – starting safely

k9s reads the same kubeconfig. K9S_CONFIG_DIR from the .envrc keeps its configuration in the lab too – k9s info shows the paths.

Open prod read-only – via flag or permanently per context:

k9s --context kunde-prod --readonly
mkdir -p ~/term-lab/kube/k9s/clusters/kunde-prod/kunde-prod
cat > ~/term-lab/kube/k9s/clusters/kunde-prod/kunde-prod/config.yaml <<'EOF'
k9s:
  cluster: kunde-prod
  readOnly: true
EOF

Without a reachable cluster, k9s only shows a connection error – quit with :q. The format of the context config may differ depending on the k9s version; k9s info names the valid folder.

Key in k9s Effect Mnemonic
: + pods, deploy, ctx pick resource/context like a vim command
/ filter like less
l / d / s logs / describe / shell logs, describe, shell
Ctrl-d delete (with confirmation) blocked in readOnly

Save your progress? Sign up for free

Drill 9: Feedback loops – entr, watch, hyperfine

entr runs a command as soon as one of the given files changes. -c clears the screen first.

fd -e go | entr -c go test ./...
fd -e sh . scripts | entr -c shellcheck /_

Why /_? It’s a placeholder for the most recently changed file. Quit with q or Ctrl-c.

watch repeats a command at an interval. Without watch, a loop does it:

watch -n 2 'kubectl get pods'
while sleep 2; do clear; date; kubectl config current-context; done

hyperfine measures instead of guessing. What does the completion from Drill 6 cost at shell startup?

D=~/term-lab/zcompdump-test
hyperfine -N --warmup 3 \
  "zsh -fc 'autoload -Uz compinit; compinit -d $D'" \
  "zsh -fc 'autoload -Uz compinit; compinit -d $D; source <(kubectl completion zsh)'"
rm -f $D

Expected (shortened, times depend on your Mac):

Benchmark 1: zsh -fc 'autoload -Uz compinit; compinit -d …' (15 runs)
  Wall Time     22.7 ms  ±     0.6 ms      21.8 ms  …    23.7 ms
Benchmark 2: zsh -fc 'autoload -Uz compinit; compinit -d …; source <(kubectl …
  Wall Time     48.8 ms  ±     3.9 ms      44.9 ms  …    59.1 ms   +115.5% (2.2x slower)

Save your progress? Sign up for free

Checkpoint

#!/usr/bin/env bash
cd ~/term-lab/projekt && eval "$(direnv export bash 2>/dev/null)"
ok() { echo "✔ $1"; }; nok() { echo "✘ $1"; }
direnv status --json | jq -e '.state.foundRC.allowed == 0' >/dev/null \
  && ok ".envrc freigegeben" || nok ".envrc freigegeben"
git check-ignore -q .env.local \
  && ok ".env.local ignoriert" || nok ".env.local ignoriert"
grep -q '^go = ' mise.toml && ok "mise: Go gepinnt" || nok "mise: Go gepinnt"
[[ $KUBECONFIG == "$HOME/term-lab/kube/config" ]] \
  && ok "Lab-kubeconfig aktiv" || nok "Lab-kubeconfig aktiv"
[[ $(kubectl config get-contexts -o name | wc -l) -ge 3 ]] \
  && ok "mind. 3 Lab-Kontexte" || nok "mind. 3 Lab-Kontexte"
[[ $(kubectl config current-context) != *prod* ]] \
  && ok "nicht auf prod" || nok "nicht auf prod"
shellcheck scripts/*.sh && ok "Skripte shellcheck-sauber" || nok "shellcheck"
make -s help | grep -q report && ok "make help" || nok "make help"

Expected:

✔ .envrc freigegeben
✔ .env.local ignoriert
✔ mise: Go gepinnt
✔ Lab-kubeconfig aktiv
✔ 3 Lab-Kontexte
✔ nicht auf prod
✔ Skripte shellcheck-sauber
✔ make help

Challenge

Extend the prod guard: kubectl exec should also ask on *prod*. For scripts that deliberately run against prod, KUBECTL_PROD_OK=1 turns off the confirmation.

Hint: In zsh you check an empty variable with -z ${VAR:-} – that stays safe with set -u too.

Solution

In ~/term-lab/config/zsh/k8s.zsh, replace the condition, then exec zsh:

  if [[ $ctx == *prod* && -z ${KUBECTL_PROD_OK:-} \
        && $verb == (apply|create|delete|edit|exec|patch|replace\
|scale|rollout|drain|cordon|label|annotate|set) ]]; then
kubectx kunde-prod >/dev/null
k exec web-1 -- id; echo "rc=$?"
KUBECTL_PROD_OK=1 k delete pod web-1 --request-timeout=2s
kubectx kind-lab >/dev/null

Expected (type n at the first command):

ACHTUNG: kubectl exec auf Kontext 'kunde-prod'
Wirklich ausführen? [y/N] n
rc=1
Unable to connect to the server: dial tcp: lookup prod.k8s.kunde.example: no such host

Clean up after the day: rm -f ~/term-lab/unsicher.sh. You’ll still need the lab kubeconfig and mise.toml on Day 15.

Save your progress? Sign up for free

Enterprise Note

  • One kubeconfig per client/project (via direnv), never all clusters in ~/.kube/config. Prod access with short-lived tokens (OIDC, kubelogin), not with static tokens.
  • The shell guard is convenience, not security: real boundaries are drawn by RBAC (prod read-only for humans), admission policies and GitOps (changes only via merge request).
  • Check .envrc into the team repo; fetch secrets from it only via Vault/OpenBao, 1Password or SOPS. Confirm direnv allow deliberately after every pull.
  • mise.toml (or .tool-versions) is the single source for versions – locally and in CI (jdx/mise-action).
  • shellcheck as a pre-commit hook and CI step. Scripts without set -euo pipefail don’t pass review.