Skip to content

Latest commit

 

History

52 Commits

Folders and files

NameName
Last commit message
Last commit date
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

kns - Kubernetes Namespace/Context Switcher

kns badge

A bash/zsh tool that automatically switches kubectl context and namespace based on your current directory. kns uses .kns.conf files to manage Kubernetes contexts per project.

Features

  • 🚀 Automatic context switching - Changes kubectl context when you cd into a directory
  • 📁 Directory-based configuration - Uses .kns.conf files (similar to asdf's .tool-versions)
  • 🔄 Parent directory lookup - Finds and merges .kns.conf from current and parent directories
  • Quick kubectl shortcuts - Fast access to common kubectl commands
  • 🐳 Pod debug - Set current pod/container per directory for easy access
  • 🐚 Bash & Zsh compatible - Works on both shells
  • ⌨️ Shell completions - Tab-complete commands; optional live kubectl values

Installation

One-Line Install (Recommended)

Install with a single command:

bash -c "$(curl -fsSL https://raw.githubusercontent.com/nbu/kns/main/install-standalone.sh)"

Or if you prefer to review the installer first:

curl -fsSL https://raw.githubusercontent.com/nbu/kns/main/install-standalone.sh -o /tmp/install-kns.sh
bash /tmp/install-kns.sh

Note: The installer will automatically:

  • Download the kns and kns.sh scripts
  • Install them to ~/.local/bin (or custom INSTALL_DIR)
  • Add them to your PATH
  • Set up shell integration
  • Offer shell Tab completions (on a TTY); non-interactive installs use static completions by default

Quick Install (From Git)

git clone https://github.com/nbu/kns.git
cd kns
./install.sh
source ~/.bashrc  # or ~/.zshrc

Manual Install

  1. Copy the kns and kns.sh scripts to a directory in your PATH:

    cp kns kns.sh ~/.local/bin/
    chmod +x ~/.local/bin/kns
  2. Add to your ~/.bashrc or ~/.zshrc:

    export PATH="$HOME/.local/bin:$PATH"
    source ~/.local/bin/kns.sh

    Adding kns to PATH alone gives you the CLI only. Sourcing kns.sh is required for automatic context switching when you change directories (zsh: chpwd hook; bash: wraps cd, pushd, and popd).

  3. Reload your shell:

    source ~/.bashrc  # or ~/.zshrc

Shell completions

kns supports Tab completion for bash and zsh.

  • static (default): subcommands only
  • live: subcommands plus kubectl contexts, namespaces, pods, and containers
kns completion install --mode static   # or --mode live
kns completion mode live               # switch mode without reinstall
kns completion uninstall

Installer prompts ask whether to install completions (and which mode). Non-interactive installs wire static completions automatically.

Advanced (manual wiring):

eval "$(kns completion zsh)"   # or: kns completion bash

Usage

Setting up a directory

Navigate to your project directory and set the context:

cd /path/to/my-project
kns set production-cluster production

This creates a .kns.conf file in the current directory:

# Auto-generated by kns
KNS_CONTEXT="production-cluster"
KNS_NAMESPACE="production"

Now, whenever you cd into this directory (or any subdirectory), the context will automatically switch to production-cluster with namespace production.

Note: You can have different properties in different .kns.conf files. For example:

  • Parent directory can have KNS_CONTEXT and KNS_NAMESPACE
  • Current directory can have KNS_POD and KNS_CONTAINER
  • Values are automatically merged when found

Named environments

A directory can define multiple named Kubernetes environments instead of a single flat context. Set KNS_ENVS and per-environment keys in .kns.conf:

# .kns.conf — multi-env example
KNS_ENVS="staging production"
KNS_DEFAULT_ENV="staging"
KNS_PROMPT_ON_ENTER=1

KNS_ENV_staging_CONTEXT="staging-cluster"
KNS_ENV_staging_NAMESPACE="staging"

KNS_ENV_production_CONTEXT="production-cluster"
KNS_ENV_production_NAMESPACE="production"

When you cd into the tree, kns applies the default environment or prompts you to pick one (prompt on enter is on by default). Control prompting with:

kns env prompt          # show effective / project / global prompt setting
kns env prompt on|off   # per-project default
kns env prompt global on|off   # global default (~/.kns/config)

Switch and manage environments:

kns env                 # interactive pick (TTY)
kns env staging         # switch to named environment
kns env list            # list environments (* = active, default marked)
kns env show [name]     # show env details
kns env default [name]  # get or set default
kns env add <name> <context> [namespace]
kns env remove <name>

The active environment is stored for the session and lasts until you leave the directory tree (or the session is cleared). kns set is refused when KNS_ENVS is configured — use kns env add instead.

Commands

Core (directory → context)

  • kns set <context> [namespace] - Set context for current directory

    kns set my-cluster my-namespace
    kns set my-cluster  # namespace is optional
  • kns env … - Select and manage named environments for a project

    kns env
    kns env staging
    kns env list
  • kns show - Show merged context/namespace/pod/container from .kns.conf

    kns show
    # Output:
    # Source: /path/to/.kns.conf
    # Context: production-cluster
    # Namespace: production
    # Pod: my-pod-123
    # Container: app
  • kns use <context> [namespace] - Switch context now; override persists until the next directory change

    kns use staging-cluster staging
  • kns list - List all available kubectl contexts

    kns list
  • kns unset - Remove .kns.conf from the current directory (all local kns settings)

    kns unset

Kubectl Shortcuts

  • kns pods - kubectl get pods
  • kns svc - kubectl get services
  • kns deploy - kubectl get deployments
  • kns namespaces - kubectl get namespaces

All shortcuts automatically switch context based on .kns.conf before executing.

Pod Debug

  • kns pod set <pod-name> - Set current pod for this directory

    kns pod set my-pod-123
  • kns pod unset [-c] - Remove local pod pin (-c also removes container)

    kns pod unset
    kns pod unset -c
  • kns service set <service-name> / kns service unset - Set or clear the default service for port-forwarding

    kns service set my-api
  • kns pf [name|ports] [target] - Run a foreground port-forward using a named mapping or literal ports

    kns pf 8080:8080                 # Uses the pinned pod or service
    kns pf 8080:80 svc/my-api        # Explicit pod/, svc/, or deploy/ target
  • kns pf set <name> <ports> [target] / kns pf unset <name> - Save or remove a named port mapping

    kns pf set app 8080:80 svc/my-api
    kns pf app
  • kns pf start [name|ports] [target] - Start a port-forward in the background

  • kns pf list - List background port-forwards for the current project and environment

  • kns pf stop [name|id|all] - Stop matching background port-forwards

    kns pf start app
    kns pf list
    kns pf stop app

Background port-forwards stop automatically when you leave the project directory tree or switch named environments. Leave cleanup uses the shared runtime registry and is global across shells, so changing directory in one shell can stop a forward started for another project in a different shell.

  • kns container set <container-name> - Set current container (requires pod)

    kns container set my-container
  • kns container unset - Remove local container pin (keeps pod)

    kns container unset
  • kns containers - List containers of current pod

    kns containers
    # Output:
    # Pod: my-pod-123
    # Containers:
    #   - app (current)
    #   - sidecar
  • kns exec <command> [args...] - Execute command in current pod/container

    kns exec ls -la /tmp
    kns exec cat /etc/hosts
  • kns cp <source> <dest> - Copy files to/from pod (use pod: prefix for pod paths)

    kns cp local.txt pod:/tmp/file.txt        # Copy to pod
    kns cp pod:/tmp/file.txt local.txt       # Copy from pod
  • kns sh - Interactive shell into current pod/container

    kns sh

Examples

# Set up a project
cd ~/projects/my-app
kns set production-cluster production

# Navigate to subdirectory - context switches automatically
cd ~/projects/my-app/src
# ✓ Switched to context: production-cluster (namespace: production)

# Use kubectl shortcuts
kns pods
kns svc

# Set up pod and container for this directory
kns pod set my-pod-123
kns container set app-container
kns containers                      # List containers

# Work with the pod
kns exec ls -la /tmp
kns cp config.yaml pod:/app/config.yaml
kns sh                              # Interactive shell

# Switch to different context manually
kns use staging-cluster staging

# Remove local .kns.conf
kns unset

Advanced: Merged Configuration

You can split configuration across multiple directories:

# In parent directory (~/projects/my-app/.kns.conf)
KNS_CONTEXT="production-cluster"
KNS_NAMESPACE="production"

# In subdirectory (~/projects/my-app/frontend/.kns.conf)
KNS_POD="frontend-pod-123"
KNS_CONTAINER="nginx"

# When in frontend/, kns will use:
# - Context/namespace from parent directory
# - Pod/container from current directory

Migration from previous command names

Breaking rename (no shims). Old names print a redirect hint:

Old New
kns current kns show
kns unlink kns unset
kns link … kns set …
kns gp kns pods
kns gs kns svc
kns gd kns deploy
kns ns kns namespaces
kns sp kns pod set
kns sc kns container set
kns gc kns containers

How it works

  1. Configuration files: kns looks for .kns.conf files walking up from the current directory to /, and also checks ~/.kns.conf (unless it was already found in the walk). Files are sourced farthest-parent to closest-child so nearer directories override parent values.

  2. Automatic switching: When kns.sh is sourced, directory changes trigger a context switch:

    • zsh: a chpwd hook runs after every cd, pushd, or popd
    • bash: cd, pushd, and popd are wrapped to run the same logic after a successful directory change
    • Clears any kns use manual override, merges .kns.conf files, then applies either the selected named environment or the flat KNS_CONTEXT/KNS_NAMESPACE settings
  3. Manual override: kns use switches kubectl immediately and writes a temporary override file. CLI commands and auto-switch honor it until you change directories (the hook clears the override and .kns.conf applies again).

  4. Named environments: When KNS_ENVS is configured, the active environment is validated against that list and its context, namespace, pod, and container pins are used together. Mutating pod commands refuse to use an ambient kubectl context when no environment is active.

  5. Manual commands and pod debug: Commands can be used manually, and shortcuts apply the resolved context before kubectl. Pod pins are stored in .kns.conf; kns exec, kns cp, and kns sh use the resolved pod and container.

Security

.kns.conf files are sourced as shell code (not parsed as data). Only use .kns.conf files in directories you trust, and do not commit untrusted config into your projects.

Configuration

Home directory config

You can set defaults for any directory under $HOME with ~/.kns.conf. It is merged like project .kns.conf files (parent → child; child wins). If your current path is under $HOME, the home file is included only once.

Project keys

Alongside KNS_CONTEXT, KNS_NAMESPACE, KNS_POD, and KNS_CONTAINER, a project can pin a default service with KNS_SERVICE. Named port mappings use:

KNS_SERVICE="my-api"
KNS_FORWARDS="app metrics"
KNS_FORWARD_DEFAULT="app"
KNS_FORWARD_app="8080:80"
KNS_FORWARD_app_TARGET="svc/my-api"
KNS_FORWARD_metrics="9090:9090"
KNS_FORWARD_metrics_TARGET="deploy/metrics"

KNS_FORWARDS is the space-separated mapping list. Each KNS_FORWARD_<name> stores ports, its optional _TARGET overrides the pinned pod or service, and KNS_FORWARD_DEFAULT selects the mapping used by bare kns pf.

For named environments, use the same keys under the environment prefix: KNS_ENV_<name>_SERVICE, KNS_ENV_<name>_FORWARDS, KNS_ENV_<name>_FORWARD_<mapping>, KNS_ENV_<name>_FORWARD_<mapping>_TARGET, and KNS_ENV_<name>_FORWARD_DEFAULT.

Runtime configuration directory

KNS_CONFIG_DIR (default: ~/.kns) stores runtime and global state:

  • manual_override — the temporary context selected by kns use
  • active_env — the active named-environment session
  • config — global settings such as prompt_on_enter
  • pf/ — background port-forward registry records and logs

To use another location:

export KNS_CONFIG_DIR="$HOME/.config/kns"

Quiet Mode

To disable the automatic context switch messages, set:

export KNS_QUIET=1

Custom Install Directory

Set INSTALL_DIR before running install:

INSTALL_DIR=/usr/local/bin ./install.sh

Requirements

  • bash or zsh
  • kubectl installed and configured
  • Write access to ~/.local/bin (or custom install directory)

Troubleshooting

Context not switching automatically

  • Make sure you've sourced kns.sh in your shell rc file
  • Check that .kns.conf exists in the directory (or parent directory)
  • Verify the file contains KNS_CONTEXT variable
  • Try running kns show to see if the file is detected and what values are being used

Pod/Container not found

  • Make sure you've set the pod with kns pod set <pod-name>
  • Verify the pod exists: kubectl get pod <pod-name>
  • Check that you're in the correct context/namespace
  • Run kns show to see current configuration

Command not found in container

  • Some minimal/distroless containers don't have common commands like ls or shells
  • Try using full paths to executables: kns exec /app/my-binary
  • Use kubectl exec directly if you know the executable path
  • Check what's available: kubectl exec <pod> -- ls /bin /usr/bin

kubectl command not found

  • Ensure kubectl is installed and in your PATH
  • Verify with which kubectl

Permission denied

  • Make sure kns script is executable: chmod +x kns
  • Check that install directory is writable

License

This project is licensed under the MIT License - see the LICENSE file for details.

Releases

Packages

Contributors

Languages