Skip to content
Hands-on IT IT Drills

Day 5: CLIs with flag and cobra – kctxsafe

Goal: Build a CLI that shows kubeconfig contexts and allows switching to prod only with confirmation · Duration: approx. 120 min · Prerequisite: Day 4

Briefing

  • kctxsafe list|current|use – a seat belt around kubectl config.
  • First flag from the standard library, then a rebuild on cobra with subcommands.
  • Configuration in a fixed order: default < file < env < flag.
  • os/exec calls kubectl – always with an explicit --kubeconfig, never the default file.
  • Tests replace kubectl with a function: no cluster, no real kubeconfig.
kctxsafe use prod-eu
   |-- setup: --kubeconfig/$KUBECONFIG, config file, $KCTXSAFE_PROD_PATTERN
   |-- prod? --> have the name typed --> wrong: abort, Exit 1
   '-- kubectl config use-context prod-eu --kubeconfig <file>

Security: In this chapter you work exclusively with lab-kubeconfig.yaml in the lab folder. Your real ~/.kube/config stays untouched – kctxsafe deliberately has no fallback to it.

Drill 1: Module and lab kubeconfig

mkdir -p ~/go-lab/tag05-kctxsafe && cd ~/go-lab/tag05-kctxsafe
go mod init example.com/kctxsafe
mkdir -p cmd/kctxsafe internal/kube internal/config internal/guard

Expected:

go: creating new go.mod: module example.com/kctxsafe

The lab kubeconfig contains three made-up clusters. The servers don’t exist – kubectl config only reads and writes the file.

cat > lab-kubeconfig.yaml <<'EOF'
apiVersion: v1
clusters:
- cluster:
    server: https://127.0.0.1:6443
  name: dev
- cluster:
    server: https://127.0.0.1:6445
  name: prod
- cluster:
    server: https://127.0.0.1:6444
  name: staging
contexts:
- context:
    cluster: dev
    namespace: default
    user: lab
  name: kind-dev
- context:
    cluster: prod
    user: lab
  name: prod-eu
- context:
    cluster: staging
    user: lab
  name: staging
current-context: kind-dev
kind: Config
users:
- name: lab
  user:
    token: lab-token-1234
EOF
export KUBECONFIG=$PWD/lab-kubeconfig.yaml   # only in this shell
kubectl config get-contexts -o name
kubectl config current-context

Expected:

kind-dev
prod-eu
staging
kind-dev

Warning: Open a separate terminal session for this chapter. That way a forgotten export KUBECONFIG can’t hit any other shell.

Save your progress? Sign up for free

Drill 2: kubectl via os/exec

kube.Client encapsulates exactly one kubeconfig file. The Runner is a function type – os/exec in production, a dummy in the test.

cat > internal/kube/kube.go <<'EOF'
// Package kube calls kubectl – always with an explicit --kubeconfig.
package kube

import (
    "context"
    "errors"
    "fmt"
    "os"
    "os/exec"
    "strings"
)

// Runner runs a program and returns stdout. In tests you replace it.
type Runner func(ctx context.Context, name string, args ...string) ([]byte, error)

// ExecRunner starts the real program via os/exec.
func ExecRunner(ctx context.Context, name string, args ...string) ([]byte, error) {
    out, err := exec.CommandContext(ctx, name, args...).Output()
    var ee *exec.ExitError
    if errors.As(err, &ee) {
        return nil, fmt.Errorf("%s: %s", name, strings.TrimSpace(string(ee.Stderr)))
    }
    return out, err
}

// Client encapsulates kubectl config for exactly one kubeconfig file.
type Client struct {
    Kubeconfig string
    Run        Runner
}

func (c Client) config(ctx context.Context, args ...string) (string, error) {
    if c.Kubeconfig == "" {
        return "", errors.New("keine Kubeconfig angegeben")
    }
    if _, err := os.Stat(c.Kubeconfig); err != nil {
        return "", err
    }
    args = append([]string{"config"}, args...)
    args = append(args, "--kubeconfig", c.Kubeconfig)
    out, err := c.Run(ctx, "kubectl", args...)
    return strings.TrimSpace(string(out)), err
}

// Contexts lists all context names.
func (c Client) Contexts(ctx context.Context) ([]string, error) {
    out, err := c.config(ctx, "get-contexts", "-o", "name")
    if err != nil {
        return nil, err
    }
    return strings.Fields(out), nil
}

// Current returns the active context.
func (c Client) Current(ctx context.Context) (string, error) {
    return c.config(ctx, "current-context")
}

// Use sets the active context.
func (c Client) Use(ctx context.Context, name string) error {
    _, err := c.config(ctx, "use-context", name)
    return err
}
EOF

Why? On an exit code ≠ 0, cmd.Output() stores stderr in *exec.ExitError; with errors.As (Day 3) you get kubectl’s own error message out of it. CommandContext terminates kubectl when the context expires or you press Ctrl+C.

Save your progress? Sign up for free

Drill 3: First attempt with flag

The flag package is enough for a tool with a single job. The default comes from the environment.

cat > cmd/kctxsafe/main.go <<'EOF'
package main

import (
    "context"
    "flag"
    "fmt"
    "os"

    "example.com/kctxsafe/internal/kube"
)

func main() {
    kubeconfig := flag.String("kubeconfig", os.Getenv("KUBECONFIG"),
        "Kubeconfig-Datei")
    flag.Parse()

    c := kube.Client{Kubeconfig: *kubeconfig, Run: kube.ExecRunner}
    cur, err := c.Current(context.Background())
    if err != nil {
        fmt.Fprintln(os.Stderr, "kctxsafe:", err)
        os.Exit(1)
    }
    fmt.Println(cur)
}
EOF
go run ./cmd/kctxsafe
go run ./cmd/kctxsafe -kubeconfig fehlt.yaml
KUBECONFIG= go run ./cmd/kctxsafe
go run ./cmd/kctxsafe -h

Expected (shortened):

kind-dev
kctxsafe: stat fehlt.yaml: no such file or directory
exit status 1
kctxsafe: keine Kubeconfig angegeben
exit status 1
Usage of /Users/.../go-build/.../kctxsafe:
  -kubeconfig string
        Kubeconfig-Datei (default "/Users/.../tag05-kctxsafe/lab-kubeconfig.yaml")

Why? flag knows only one command and simple types. For list, current and use with their own flags and help per command, cobra pays off – the framework behind kubectl, helm and gh.

Save your progress? Sign up for free

Drill 4: Config from file and env

You parse a key=value file with what you learned on Day 1 – no package needed. The environment comes in as a function, so tests don’t have to bend anything with os.Setenv.

cat > internal/config/config.go <<'EOF'
// Package config loads settings: default < file < env (< flag in main).
package config

import (
    "bufio"
    "fmt"
    "os"
    "regexp"
    "strings"
)

// Config holds the settings of kctxsafe.
type Config struct {
    ProdPattern string // regular expression for production contexts
}

// Load optionally reads a key=value file and then the environment.
func Load(path string, getenv func(string) string) (Config, error) {
    c := Config{ProdPattern: "prod"}
    if path != "" {
        if err := c.readFile(path); err != nil {
            return c, err
        }
    }
    if v := getenv("KCTXSAFE_PROD_PATTERN"); v != "" {
        c.ProdPattern = v
    }
    return c, nil
}

func (c *Config) readFile(path string) error {
    f, err := os.Open(path)
    if err != nil {
        return err
    }
    defer f.Close()
    sc := bufio.NewScanner(f)
    for n := 1; sc.Scan(); n++ {
        line := strings.TrimSpace(sc.Text())
        if line == "" || strings.HasPrefix(line, "#") {
            continue
        }
        key, val, ok := strings.Cut(line, "=")
        if !ok {
            return fmt.Errorf("%s:%d: erwartet key=value", path, n)
        }
        switch strings.TrimSpace(key) {
        case "prod_pattern":
            c.ProdPattern = strings.TrimSpace(val)
        default:
            return fmt.Errorf("%s:%d: unbekannter Schlüssel %q", path, n, key)
        }
    }
    return sc.Err()
}

// ProdRegexp compiles the pattern; the config reports errors, not the switch.
func (c Config) ProdRegexp() (*regexp.Regexp, error) {
    re, err := regexp.Compile(c.ProdPattern)
    if err != nil {
        return nil, fmt.Errorf("prod_pattern: %w", err)
    }
    return re, nil
}
EOF
go vet ./internal/...

Expected: no output.

Why? Unknown keys are an error, not silently ignored – otherwise a typo like prod_patern would switch off the protection.

Save your progress? Sign up for free

Drill 5: The safety barrier

You type a y by reflex. Typing out the context name forces you to read – the same pattern as when deleting a GitHub repo.

cat > internal/guard/guard.go <<'EOF'
// Package guard protects production contexts from accidental switching.
package guard

import (
    "bufio"
    "fmt"
    "io"
    "strings"
)

// Confirm asks for the context name. Only exactly the same name confirms.
func Confirm(in io.Reader, out io.Writer, name string) (bool, error) {
    fmt.Fprintf(out, "%s ist prod. Namen zum Bestätigen tippen: ", name)
    line, err := bufio.NewReader(in).ReadString('\n')
    if err != nil && err != io.EOF {
        return false, err
    }
    return strings.TrimSpace(line) == name, nil
}
EOF

Why? io.Reader and io.Writer instead of os.Stdin/os.Stderr: in the test, the input is a strings.Reader and the output io.Discard.

Save your progress? Sign up for free

Drill 6: Rebuild on cobra

go get github.com/spf13/[email protected]

Expected:

go: added github.com/inconshreveable/mousetrap v1.1.0
go: added github.com/spf13/cobra v1.10.2
go: added github.com/spf13/pflag v1.0.9

main stays tiny. newRoot gets the kubectl runner, the environment and stdin from the outside – exactly the three things a test wants to replace.

cat > cmd/kctxsafe/main.go <<'EOF'
// kctxsafe shows and switches kubeconfig contexts – prod only with confirmation.
package main

import (
    "context"
    "io"
    "os"
    "os/signal"

    "example.com/kctxsafe/internal/kube"
    "github.com/spf13/cobra"
)

func main() {
    ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt)
    defer stop()
    root := newRoot(kube.ExecRunner, os.Getenv, os.Stdin)
    if err := root.ExecuteContext(ctx); err != nil {
        os.Exit(1)
    }
}

// newRoot builds the command tree; dependencies come from outside (testable).
func newRoot(run kube.Runner, getenv func(string) string, in io.Reader,
) *cobra.Command {
    a := &app{run: run, getenv: getenv, in: in}
    root := &cobra.Command{
        Use:          "kctxsafe",
        Short:        "kubeconfig-Kontexte anzeigen und sicher wechseln",
        SilenceUsage: true,
    }
    pf := root.PersistentFlags()
    pf.StringVar(&a.kubeconfig, "kubeconfig", "", "Kubeconfig (sonst $KUBECONFIG)")
    pf.StringVar(&a.configFile, "config", "", "Config (sonst $KCTXSAFE_CONFIG)")
    pf.StringVar(&a.prodPattern, "prod-pattern", "", "Regex für prod-Kontexte")
    root.AddCommand(a.listCmd(), a.currentCmd(), a.useCmd())
    return root
}
EOF

The subcommands hang off app. setup enforces the order flag > env > file > default in one single place.

cat > cmd/kctxsafe/app.go <<'EOF'
package main

import (
    "errors"
    "fmt"
    "io"
    "regexp"
    "strings"

    "example.com/kctxsafe/internal/config"
    "example.com/kctxsafe/internal/guard"
    "example.com/kctxsafe/internal/kube"
    "github.com/spf13/cobra"
)

type app struct {
    run                                 kube.Runner
    getenv                              func(string) string
    in                                  io.Reader
    kubeconfig, configFile, prodPattern string
}

// setup evaluates flag > env > file > default.
func (a *app) setup() (kube.Client, *regexp.Regexp, error) {
    path := first(a.kubeconfig, a.getenv("KUBECONFIG"))
    if path == "" {
        return kube.Client{}, nil, errors.New("--kubeconfig oder KUBECONFIG setzen")
    }
    if strings.Contains(path, ":") {
        return kube.Client{}, nil, errors.New("genau eine Kubeconfig-Datei erlaubt")
    }
    cfg, err := config.Load(first(a.configFile, a.getenv("KCTXSAFE_CONFIG")), a.getenv)
    if err != nil {
        return kube.Client{}, nil, err
    }
    if a.prodPattern != "" {
        cfg.ProdPattern = a.prodPattern
    }
    re, err := cfg.ProdRegexp()
    return kube.Client{Kubeconfig: path, Run: a.run}, re, err
}

func first(vals ...string) string {
    for _, v := range vals {
        if v != "" {
            return v
        }
    }
    return ""
}

func (a *app) listCmd() *cobra.Command {
    return &cobra.Command{
        Use:   "list",
        Short: "Kontexte auflisten (* = aktiv)",
        Args:  cobra.NoArgs,
        RunE: func(cmd *cobra.Command, _ []string) error {
            c, prod, err := a.setup()
            if err != nil {
                return err
            }
            names, err := c.Contexts(cmd.Context())
            if err != nil {
                return err
            }
            cur, _ := c.Current(cmd.Context()) // no active context is ok
            for _, n := range names {
                mark, tag := " ", ""
                if n == cur {
                    mark = "*"
                }
                if prod.MatchString(n) {
                    tag = "  [PROD]"
                }
                fmt.Fprintf(cmd.OutOrStdout(), "%s %s%s\n", mark, n, tag)
            }
            return nil
        },
    }
}

func (a *app) currentCmd() *cobra.Command {
    return &cobra.Command{
        Use:   "current",
        Short: "aktiven Kontext anzeigen",
        Args:  cobra.NoArgs,
        RunE: func(cmd *cobra.Command, _ []string) error {
            c, _, err := a.setup()
            if err != nil {
                return err
            }
            cur, err := c.Current(cmd.Context())
            if err != nil {
                return err
            }
            fmt.Fprintln(cmd.OutOrStdout(), cur)
            return nil
        },
    }
}

func (a *app) useCmd() *cobra.Command {
    var yes bool
    cmd := &cobra.Command{
        Use:   "use KONTEXT",
        Short: "Kontext wechseln (prod nur mit Bestätigung)",
        Args:  cobra.ExactArgs(1),
        RunE: func(cmd *cobra.Command, args []string) error {
            c, prod, err := a.setup()
            if err != nil {
                return err
            }
            name := args[0]
            if prod.MatchString(name) && !yes {
                ok, err := guard.Confirm(a.in, cmd.ErrOrStderr(), name)
                if err != nil {
                    return err
                }
                if !ok {
                    return errors.New("abgebrochen, Kontext unverändert")
                }
            }
            if err := c.Use(cmd.Context(), name); err != nil {
                return err
            }
            fmt.Fprintf(cmd.OutOrStdout(), "Kontext jetzt: %s\n", name)
            return nil
        },
    }
    cmd.Flags().BoolVarP(&yes, "yes", "y", false, "ohne Rückfrage (für Skripte)")
    return cmd
}
EOF
go mod tidy
go build -o kctxsafe ./cmd/kctxsafe
./kctxsafe list
./kctxsafe use staging
echo nein | ./kctxsafe use prod-eu; echo "Exit: $?"
echo prod-eu | ./kctxsafe use prod-eu
./kctxsafe use kind-dev

Expected:

* kind-dev
  prod-eu  [PROD]
  staging
Kontext jetzt: staging
prod-eu ist prod. Namen zum Bestätigen tippen: Error: abgebrochen, Kontext unverändert
Exit: 1
prod-eu ist prod. Namen zum Bestätigen tippen: Kontext jetzt: prod-eu
Kontext jetzt: kind-dev

Why? SilenceUsage: true prevents cobra from printing the complete help on every runtime error; errors still end up on stderr as Error: …. ExecuteContext passes the signal context through to cmd.Context() and thus all the way to kubectl. (The prompt reads “prod-eu is prod. Type the name to confirm:”, the result “Context now:” or “aborted, context unchanged”.)

Now the configuration sources against each other:

printf '# kctxsafe-Lab\nprod_pattern=prod|staging\n' > kctxsafe.conf
./kctxsafe list --config kctxsafe.conf
KCTXSAFE_CONFIG=kctxsafe.conf KCTXSAFE_PROD_PATTERN='^kind' ./kctxsafe list
./kctxsafe list --prod-pattern '('
./kctxsafe --kubeconfig a.yaml:b.yaml list
./kctxsafe use gibtsnicht

Expected:

* kind-dev
  prod-eu  [PROD]
  staging  [PROD]
* kind-dev  [PROD]
  prod-eu
  staging
Error: prod_pattern: error parsing regexp: missing closing ): `(`
Error: genau eine Kubeconfig-Datei erlaubt
Error: kubectl: error: no context exists with the name: "gibtsnicht"

Tip: ./kctxsafe completion zsh generates shell completion for free – cobra adds the command automatically.

Save your progress? Sign up for free

Drill 7: Tests with a fake kubectl

First the small packages, table-driven as on Day 4:

cat > internal/guard/guard_test.go <<'EOF'
package guard

import (
    "io"
    "strings"
    "testing"
)

func TestConfirm(t *testing.T) {
    tests := []struct {
        name, input string
        want        bool
    }{
        {"exakter Name", "prod-eu\n", true},
        {"ohne Zeilenende", "prod-eu", true},
        {"nur y", "y\n", false},
        {"leer", "", false},
        {"anderer Kontext", "prod-us\n", false},
    }
    for _, tt := range tests {
        t.Run(tt.name, func(t *testing.T) {
            got, err := Confirm(strings.NewReader(tt.input), io.Discard, "prod-eu")
            if err != nil {
                t.Fatal(err)
            }
            if got != tt.want {
                t.Errorf("Confirm(%q) = %v, want %v", tt.input, got, tt.want)
            }
        })
    }
}
EOF
cat > internal/config/config_test.go <<'EOF'
package config

import (
    "os"
    "path/filepath"
    "testing"
)

func TestLoadReihenfolge(t *testing.T) {
    path := filepath.Join(t.TempDir(), "kctxsafe.conf")
    content := "# Lab\nprod_pattern = prod|live\n"
    if err := os.WriteFile(path, []byte(content), 0o600); err != nil {
        t.Fatal(err)
    }
    env := map[string]string{}
    getenv := func(k string) string { return env[k] }

    tests := []struct {
        name, path, envVal, want string
    }{
        {"Default", "", "", "prod"},
        {"Datei", path, "", "prod|live"},
        {"Env schlägt Datei", path, "^p-", "^p-"},
    }
    for _, tt := range tests {
        t.Run(tt.name, func(t *testing.T) {
            env["KCTXSAFE_PROD_PATTERN"] = tt.envVal
            c, err := Load(tt.path, getenv)
            if err != nil {
                t.Fatal(err)
            }
            if c.ProdPattern != tt.want {
                t.Errorf("ProdPattern = %q, want %q", c.ProdPattern, tt.want)
            }
        })
    }
}
EOF

Then the CLI as a whole: newRoot with a fake runner, SetArgs instead of os.Args, output into a buffer. The most important case: y instead of the name must not trigger a use-context. The integration test uses real kubectl on a copy of the lab file in t.TempDir() and skips itself without kubectl.

cat > cmd/kctxsafe/main_test.go <<'EOF'
package main

import (
    "bytes"
    "context"
    "os"
    "os/exec"
    "path/filepath"
    "strings"
    "testing"

    "example.com/kctxsafe/internal/kube"
)

// fakeKubectl answers like kubectl and remembers whether it switched.
type fakeKubectl struct{ switched bool }

func (f *fakeKubectl) run(_ context.Context, _ string, args ...string) ([]byte, error) {
    switch args[1] {
    case "get-contexts":
        return []byte("kind-dev\nprod-eu\n"), nil
    case "current-context":
        return []byte("kind-dev\n"), nil
    case "use-context":
        f.switched = true
    }
    return nil, nil
}

// execute starts the CLI as if from the shell, just without a process.
func execute(t *testing.T, run kube.Runner, kc, stdin string, args ...string) (
    string, error) {
    t.Helper()
    root := newRoot(run, func(string) string { return "" }, strings.NewReader(stdin))
    var out bytes.Buffer
    root.SetOut(&out)
    root.SetErr(&out)
    root.SetArgs(append([]string{"--kubeconfig", kc}, args...))
    err := root.Execute()
    return out.String(), err
}

func labKubeconfig(t *testing.T) string {
    t.Helper()
    src, err := os.ReadFile("../../lab-kubeconfig.yaml")
    if err != nil {
        t.Fatal(err)
    }
    kc := filepath.Join(t.TempDir(), "kubeconfig") // copy, original stays
    if err := os.WriteFile(kc, src, 0o600); err != nil {
        t.Fatal(err)
    }
    return kc
}

func TestUse(t *testing.T) {
    tests := []struct {
        name, stdin string
        args        []string
        wantSwitch  bool
    }{
        {"dev ohne Frage", "", []string{"use", "kind-dev"}, true},
        {"prod mit y", "y\n", []string{"use", "prod-eu"}, false},
        {"prod mit Namen", "prod-eu\n", []string{"use", "prod-eu"}, true},
        {"prod mit --yes", "", []string{"use", "prod-eu", "--yes"}, true},
    }
    kc := labKubeconfig(t)
    for _, tt := range tests {
        t.Run(tt.name, func(t *testing.T) {
            f := &fakeKubectl{}
            _, err := execute(t, f.run, kc, tt.stdin, tt.args...)
            if f.switched != tt.wantSwitch || (err == nil) != tt.wantSwitch {
                t.Errorf("switched=%v err=%v, want switch %v",
                    f.switched, err, tt.wantSwitch)
            }
        })
    }
}

func TestListMarkiert(t *testing.T) {
    out, err := execute(t, (&fakeKubectl{}).run, labKubeconfig(t), "", "list")
    if want := "* kind-dev\n  prod-eu  [PROD]\n"; err != nil || out != want {
        t.Errorf("list = %q, %v; want %q", out, err, want)
    }
}

// Integration: real kubectl on a copy of the lab kubeconfig.
func TestEchtesKubectl(t *testing.T) {
    if _, err := exec.LookPath("kubectl"); err != nil {
        t.Skip("kubectl nicht installiert")
    }
    kc := labKubeconfig(t)
    if _, err := execute(t, kube.ExecRunner, kc, "", "use", "staging"); err != nil {
        t.Fatal(err)
    }
    if out, _ := execute(t, kube.ExecRunner, kc, "", "current"); out != "staging\n" {
        t.Errorf("current = %q, want staging", out)
    }
}
EOF
go test -race -count=1 ./...
go test -count=1 -v -run TestUse ./cmd/kctxsafe

Expected (shortened):

ok      example.com/kctxsafe/cmd/kctxsafe   1.382s
ok      example.com/kctxsafe/internal/config    1.421s
ok      example.com/kctxsafe/internal/guard 1.150s
?       example.com/kctxsafe/internal/kube  [no test files]
--- PASS: TestUse (0.00s)
    --- PASS: TestUse/dev_ohne_Frage (0.00s)
    --- PASS: TestUse/prod_mit_y (0.00s)
    --- PASS: TestUse/prod_mit_Namen (0.00s)
    --- PASS: TestUse/prod_mit_--yes (0.00s)
PASS

Why? Because the runner is a function, the test needs no mock framework. kube has no tests of its own but is tested along with cmd/kctxsafe – go test -coverpkg=./... ./... shows that.

Save your progress? Sign up for free

Drill 8: The tool is done

Otherwise golangci-lint (Day 0) flags every unchecked fmt.Fprintf. The std-error-handling preset excludes these standard cases:

cat > .golangci.yml <<'EOF'
version: "2"
linters:
  exclusions:
    presets: [std-error-handling] # don't flag fmt.Fprint*, Close & co.
EOF
gofmt -l . && go vet ./... && ~/go-lab/bin/lint run ./...
go build -o kctxsafe ./cmd/kctxsafe
./kctxsafe --help | tail -6
./kctxsafe use prod-eu --yes && ./kctxsafe current && ./kctxsafe use kind-dev

Expected:

0 issues.
      --config string         Config (sonst $KCTXSAFE_CONFIG)
  -h, --help                  help for kctxsafe
      --kubeconfig string     Kubeconfig (sonst $KUBECONFIG)
      --prod-pattern string   Regex für prod-Kontexte

Use "kctxsafe [command] --help" for more information about a command.
Kontext jetzt: prod-eu
prod-eu
Kontext jetzt: kind-dev

With your real setup you would later call kctxsafe deliberately with --kubeconfig ~/.kube/config – not in the lab.

Save your progress? Sign up for free

Checkpoint

cd ~/go-lab/tag05-kctxsafe && export KUBECONFIG=$PWD/lab-kubeconfig.yaml
ok() { echo "✔ $1"; }; nok() { echo "✘ $1"; }
go vet ./... && go test -count=1 ./... >/dev/null && ok "vet + Tests" || nok "Tests"
./kctxsafe list | grep -q 'prod-eu  \[PROD\]' && ok "prod markiert" || nok "list"
echo y | ./kctxsafe use prod-eu 2>/dev/null && nok "prod ohne Namen" \
  || ok "prod blockiert"
[ "$(./kctxsafe current)" = kind-dev ] && ok "Kontext unverändert" || nok "current"
KUBECONFIG= ./kctxsafe list 2>/dev/null && nok "Fallback!" || ok "kein Fallback"

Expected:

✔ vet + Tests
✔ prod markiert
✔ prod blockiert
✔ Kontext unverändert
✔ kein Fallback

Challenge

Build kctxsafe check: exit code 0 if the active context is not prod, otherwise exit code 2 – for the shell prompt or as a guard before helm upgrade in scripts.

Hint: cobra only knows “error or not”; define a sentinel error (Day 3) and evaluate it in main with errors.Is.

Solution

Append to app.go:

cat >> cmd/kctxsafe/app.go <<'EOF'

// errProd tells main: the active context is prod -> exit code 2.
var errProd = errors.New("aktiver Kontext ist prod")

func (a *app) checkCmd() *cobra.Command {
    return &cobra.Command{
        Use:   "check",
        Short: "Exit 2, wenn der aktive Kontext prod ist (für Prompt/CI)",
        Args:  cobra.NoArgs,
        RunE: func(cmd *cobra.Command, _ []string) error {
            c, prod, err := a.setup()
            if err != nil {
                return err
            }
            cur, err := c.Current(cmd.Context())
            if err != nil {
                return err
            }
            if prod.MatchString(cur) {
                return errProd
            }
            return nil
        },
    }
}
EOF

In main.go, register the command (root.AddCommand(…, a.checkCmd())), import "errors" and distinguish the exit code:

    if err := root.ExecuteContext(ctx); err != nil {
        if errors.Is(err, errProd) {
            os.Exit(2)
        }
        os.Exit(1)
    }
go build -o kctxsafe ./cmd/kctxsafe
./kctxsafe check; echo "Exit: $?"
./kctxsafe use prod-eu -y >/dev/null; ./kctxsafe check; echo "Exit: $?"
./kctxsafe use kind-dev

Expected:

Exit: 0
Error: aktiver Kontext ist prod
Exit: 2
Kontext jetzt: kind-dev

Save your progress? Sign up for free

Enterprise Note

  • Real kubeconfigs contain tokens and client certificates: file mode 0600, never into the repo; better yet, short-lived credentials via an exec plugin (OIDC, kubelogin, Vault/OpenBao Kubernetes secrets engine).
  • A separate kubeconfig file per environment (KUBECONFIG=~/.kube/prod.yaml only in the prod shell) is more robust than a context switch in a shared file.
  • The confirmation does not replace RBAC: prod permissions belong to a separate role with approval (break glass), not to every developer account.
  • Never use os/exec with sh -c and concatenated strings – always pass arguments individually, otherwise you get command injection.
  • For a team rollout: distribute the binary via a release (Day 14), ship it with a version via -ldflags (Day 0) and shell completion.