kubectl shell alias for listing pods across all namespaces sorted by creation time

devops-kubernetes

What we’re building

We are defining a persistent shell alias, kgpa, that expands to kubectl get pods --all-namespaces -o wide --sort-by=.metadata.creationTimestamp. This gives you a sorted, wide-format view of every pod in the cluster with a single short command. You would reach for this pattern any time a repetitive multi-flag kubectl invocation is slowing down your daily debugging or on-call workflow.

Prerequisites

  • Bash 5.x or Zsh 5.9+ (Fish is supported with a different syntax, noted where relevant)
  • kubectl 1.28 or later installed and on your PATH
  • A reachable Kubernetes cluster — local kind or minikube is sufficient for testing
  • A valid kubeconfig at ~/.kube/config or a KUBECONFIG environment variable pointing to one or more config files
  • Basic familiarity with kubeconfig contexts and switching between them

Understanding the repetitive command pattern

The raw command we are replacing is:

kubectl get pods --all-namespaces -o wide --sort-by=.metadata.creationTimestamp

Typed correctly, this command lists every pod across every namespace, includes node assignment and IP columns via -o wide, and orders results oldest-first using a JSONPath expression against .metadata.creationTimestamp. That ordering makes it straightforward to spot recently scheduled or recently restarting pods at the bottom of the list.

The problem is mechanical: the command is 76 characters long, contains three flags you must remember in full, and the JSONPath field path must be exact. If you mistype the field path, kubectl does not raise an error — it silently returns unsorted output. Typing this command dozens of times per shift introduces both friction and a subtle correctness risk. An alias eliminates both.

Before naming your alias, verify that the name does not collide with a kubectl plugin. Run kubectl plugin list and confirm kgpa does not appear. Plugin managers such as krew register short names, and a collision will cause unpredictable behavior. Also avoid aliasing kubectl itself — for example, alias kubectl='kubectl --context=prod' — because that pattern silently routes every kubectl call to a specific cluster and is a common source of accidental production operations.

Writing the alias and adding it to your shell profile

The following file contains the core alias, a companion shell function for namespace-scoped queries, and a context guard helper. Add this block to your shell profile — ~/.bashrc for Bash on Linux, ~/.zshrc for Zsh, or ~/.config/fish/config.fish for Fish with adapted syntax.

A common mistake on Linux is placing the alias in ~/.bash_profile instead of ~/.bashrc. The ~/.bash_profile file is sourced only for login shells, so the alias will be absent in the non-login interactive terminals you open from a desktop environment or a terminal multiplexer like tmux. Use ~/.bashrc for anything you want available in every interactive session.

#!/usr/bin/env bash
# File: ~/.bashrc (or ~/.zshrc)
# Purpose: Productive kubectl aliases for daily Kubernetes work
# Tested with: kubectl 1.28+, bash 5.x, zsh 5.9

# ---------------------------------------------------------------------------
# CORE ALIAS
# Lists all pods across namespaces, wide output, sorted oldest-first.
# Use case: quickly spot recently crashed or restarting pods.
# ---------------------------------------------------------------------------
alias kgpa='kubectl get pods \
  --all-namespaces \
  -o wide \
  --sort-by=.metadata.creationTimestamp'

# ---------------------------------------------------------------------------
# SAFER ALTERNATIVE AS A FUNCTION
# Accepts an optional namespace argument.
# Usage:
#   kgp            -> all namespaces
#   kgp kube-system -> only kube-system namespace
# ---------------------------------------------------------------------------
kgp() {
  if [ -z "$1" ]; then
    kubectl get pods \
      --all-namespaces \
      -o wide \
      --sort-by=.metadata.creationTimestamp
  else
    kubectl get pods \
      --namespace "$1" \
      -o wide \
      --sort-by=.metadata.creationTimestamp
  fi
}

# ---------------------------------------------------------------------------
# CONTEXT-AWARE GUARD
# Prints current context before any destructive-ish operation.
# Wrap apply/delete commands with this to avoid wrong-cluster mistakes.
# ---------------------------------------------------------------------------
kctx-check() {
  local current_context
  current_context=$(kubectl config current-context 2>/dev/null)
  if [ -z "$current_context" ]; then
    echo "ERROR: No active kubeconfig context found." >&2
    return 1
  fi
  echo "Active context: ${current_context}"
}

The alias definition is a single expanded string. The shell function kgp accepts an optional positional argument $1; when provided, it scopes the query to that namespace. This is the correct pattern when you need dynamic arguments — aliases cannot accept positional parameters, so a function is the right tool for that case. The kctx-check function is a lightweight guard you can call before any command that modifies cluster state.

Reloading the shell and verifying the alias

After saving the profile file, reload it in your current session. Do not open a new terminal tab and assume the alias is present — reload explicitly so you can catch errors immediately.

# For Bash
source ~/.bashrc

# For Zsh
source ~/.zshrc

Once the profile is sourced, use the type built-in to confirm the alias and function loaded correctly. The type command is more informative than alias alone because it distinguishes between aliases, functions, and external binaries.

# Confirm the alias definition
type kgpa
# Expected output:
# kgpa is an alias for 'kubectl get pods   --all-namespaces   -o wide   --sort-by=.metadata.creationTimestamp'

# Confirm the function is registered
type kgp
# Expected output:
# kgp is a function

# Confirm the context guard loaded
type kctx-check
# Expected output:
# kctx-check is a function

# Verify the active context before running against a real cluster
kctx-check
# Expected output:
# Active context: <your-context-name>

Run kgpa against your cluster and confirm the output is sorted by creation time with the most recently created pods at the bottom. If the output appears unsorted, double-check the JSONPath value — .metadata.creationTimestamp must match exactly. A typo in the field path causes kubectl to return results in default order without any warning.

Scoping the alias safely across multiple kubeconfig contexts

When you work with multiple clusters — for example, a local development cluster alongside staging and production remotes — the alias itself requires no modification because it does not hard-code a context. The active context is determined by your kubeconfig, which you switch with kubectl config use-context <name> or a tool like kubectx.

If you maintain separate kubeconfig files, set the KUBECONFIG environment variable to a colon-separated list of paths before sourcing your profile:

# Example: merge two kubeconfig files at shell startup
export KUBECONFIG="$HOME/.kube/config:$HOME/.kube/config-staging"

With this in place, kgpa and kgp will operate against whichever context is currently active across all merged files. Call kctx-check before running any command that modifies resources to confirm you are pointed at the intended cluster. This is especially important in workflows where you switch contexts frequently during an incident response session.

If you want the alias available inside non-interactive scripts or CI containers, an alias definition in a shell profile will not be sourced automatically. In that case, convert the alias to a small executable script and place it under /usr/local/bin/kgpa with execute permissions, or source the profile explicitly at the top of your script with source ~/.bashrc after confirming the environment supports it.

What to do next

  • Extend the kgp function pattern to other frequent kubectl commands — for example, a function that accepts a label selector as an argument for filtered pod lookups.
  • Store your aliases and functions in a dotfiles repository and add a setup script that symlinks the relevant files. Source the same file in CI container images so team members and pipelines share identical shortcuts.
  • Audit your active aliases periodically with alias (no arguments) to identify stale shortcuts that reference removed namespaces, decommissioned clusters, or flags that have changed meaning across kubectl versions.
  • Review the kubectl krew plugin list after any new plugin installation to confirm no newly installed plugin name conflicts with an existing alias in your profile.

official docs

Leave a Reply

Your email address will not be published. Required fields are marked *

Support us · 💳 Monobank