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.
- 🚀 Automatic context switching - Changes kubectl context when you
cdinto a directory - 📁 Directory-based configuration - Uses
.kns.conffiles (similar to asdf's.tool-versions) - 🔄 Parent directory lookup - Finds and merges
.kns.conffrom 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
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.shNote: The installer will automatically:
- Download the
knsandkns.shscripts - Install them to
~/.local/bin(or customINSTALL_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
git clone https://github.com/nbu/kns.git
cd kns
./install.sh
source ~/.bashrc # or ~/.zshrc-
Copy the
knsandkns.shscripts to a directory in your PATH:cp kns kns.sh ~/.local/bin/ chmod +x ~/.local/bin/kns
-
Add to your
~/.bashrcor~/.zshrc:export PATH="$HOME/.local/bin:$PATH" source ~/.local/bin/kns.sh
Adding
knsto PATH alone gives you the CLI only. Sourcingkns.shis required for automatic context switching when you change directories (zsh:chpwdhook; bash: wrapscd,pushd, andpopd). -
Reload your shell:
source ~/.bashrc # or ~/.zshrc
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 uninstallInstaller 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 bashNavigate to your project directory and set the context:
cd /path/to/my-project
kns set production-cluster productionThis 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_CONTEXTandKNS_NAMESPACE - Current directory can have
KNS_PODandKNS_CONTAINER - Values are automatically merged when found
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.
-
kns set <context> [namespace]- Set context for current directorykns set my-cluster my-namespace kns set my-cluster # namespace is optional
-
kns env …- Select and manage named environments for a projectkns env kns env staging kns env list
-
kns show- Show merged context/namespace/pod/container from.kns.confkns 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 changekns use staging-cluster staging
-
kns list- List all available kubectl contextskns list
-
kns unset- Remove.kns.conffrom the current directory (all local kns settings)kns unset
kns pods-kubectl get podskns svc-kubectl get serviceskns deploy-kubectl get deploymentskns namespaces-kubectl get namespaces
All shortcuts automatically switch context based on .kns.conf before executing.
-
kns pod set <pod-name>- Set current pod for this directorykns pod set my-pod-123 -
kns pod unset [-c]- Remove local pod pin (-calso 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-forwardingkns service set my-api -
kns pf [name|ports] [target]- Run a foreground port-forward using a named mapping or literal portskns 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 mappingkns 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-forwardskns 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 podkns containers # Output: # Pod: my-pod-123 # Containers: # - app (current) # - sidecar
-
kns exec <command> [args...]- Execute command in current pod/containerkns exec ls -la /tmp kns exec cat /etc/hosts
-
kns cp <source> <dest>- Copy files to/from pod (usepod: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/containerkns sh
# 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 unsetYou 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 directoryBreaking 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 |
-
Configuration files:
knslooks for.kns.conffiles 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. -
Automatic switching: When
kns.shis sourced, directory changes trigger a context switch:- zsh: a
chpwdhook runs after everycd,pushd, orpopd - bash:
cd,pushd, andpopdare wrapped to run the same logic after a successful directory change - Clears any
kns usemanual override, merges.kns.conffiles, then applies either the selected named environment or the flatKNS_CONTEXT/KNS_NAMESPACEsettings
- zsh: a
-
Manual override:
kns useswitches 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.confapplies again). -
Named environments: When
KNS_ENVSis 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. -
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, andkns shuse the resolved pod and container.
.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.
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.
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.
KNS_CONFIG_DIR (default: ~/.kns) stores runtime and global state:
manual_override— the temporary context selected bykns useactive_env— the active named-environment sessionconfig— global settings such asprompt_on_enterpf/— background port-forward registry records and logs
To use another location:
export KNS_CONFIG_DIR="$HOME/.config/kns"To disable the automatic context switch messages, set:
export KNS_QUIET=1Set INSTALL_DIR before running install:
INSTALL_DIR=/usr/local/bin ./install.shbashorzshkubectlinstalled and configured- Write access to
~/.local/bin(or custom install directory)
- Make sure you've sourced
kns.shin your shell rc file - Check that
.kns.confexists in the directory (or parent directory) - Verify the file contains
KNS_CONTEXTvariable - Try running
kns showto see if the file is detected and what values are being used
- 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 showto see current configuration
- Some minimal/distroless containers don't have common commands like
lsor shells - Try using full paths to executables:
kns exec /app/my-binary - Use
kubectl execdirectly if you know the executable path - Check what's available:
kubectl exec <pod> -- ls /bin /usr/bin
- Ensure
kubectlis installed and in your PATH - Verify with
which kubectl
- Make sure
knsscript is executable:chmod +x kns - Check that install directory is writable
This project is licensed under the MIT License - see the LICENSE file for details.