kube-ctx-manager

May 8, 2026 · View on GitHub

A smart shell plugin for kubectl power users — fuzzy context switching, auto-suggested aliases, and prod safeguards built right into your terminal.

Shell Requires License


Why this exists

If you manage multiple Kubernetes clusters daily, you've probably:

  • Accidentally run kubectl delete on prod instead of staging
  • Spent 30 seconds typing kubectl config use-context arn:aws:eks:ap-south-1:...
  • Forgotten your own aliases halfway through a sprint

kube-ctx-manager fixes all three. It's a single shell plugin — no daemon, no agent, no background process.


Features

FeatureWhat it does
Fuzzy context switcherkx opens an fzf picker across all your kubeconfig contexts
Alias suggesterWatches your kubectl usage and suggests aliases for long commands you repeat
Prod safeguardAny destructive command against a prod/production/live context requires explicit confirmation
Namespace switcherkns fuzzy-picks namespaces within the current context
Context labelInjects current context + namespace into your shell prompt (PS1/RPROMPT)
Audit logEvery kubectl command against a prod context is appended to ~/.kube/audit.log
Health monitoringkhealth checks cluster connectivity and response times
Kubeconfig mergingkube-merge combines multiple kubeconfig files safely
Backup & restorekube-backup creates and restores kubeconfig backups
Advanced searchksearch finds contexts by name, cluster, user, or pattern
Context bookmarkskbookmark saves favorite contexts with descriptions
Resource monitoringkmonitor shows cluster resource usage and health
Command analyticskanalytics tracks usage patterns and generates reports
Security featuresSensitive data redaction, secure file permissions, configurable security options
Context export/importkexport and kimport for sharing contexts between machines
Namespace favoriteskns-fav-add and kns-fav for quick namespace access
Context diffkdiff and kinfo for comparing contexts and viewing details
Tool integrationskk9s, khelm, kstern for seamless K9s, Helm, and Stern integration
Resource managementkquota, klimits, kpod-res, kcleanup for resource operations

Requirements

  • kubectl ≥ 1.24
  • fzf ≥ 0.35
  • Bash 4+ or Zsh 5+

Optional Dependencies

  • yq - For enhanced kubeconfig merging and validation
  • jq - For JSON processing in analytics and monitoring
  • bats-core - For running tests
  • shellcheck - For code linting

Installation

curl -fsSL https://raw.githubusercontent.com/NotHarshhaa/kube-ctx-manager/master/install.sh | bash

Manual

git clone https://github.com/NotHarshhaa/kube-ctx-manager.git
cd kube-ctx-manager
./install.sh

The installer adds a source line to your .bashrc or .zshrc automatically.

Oh My Zsh plugin

git clone https://github.com/NotHarshhaa/kube-ctx-manager.git \
  ${ZSH_CUSTOM:-~/.oh-my-zsh/custom}/plugins/kube-ctx-manager

# Add to your .zshrc plugins list:
plugins=(... kube-ctx-manager)

Usage

Context switching

kx                  # fuzzy pick from all contexts
kx staging          # switch directly if name matches
kx -                # switch back to previous context

Namespace switching

kns                 # fuzzy pick namespace in current context
kns kube-system     # switch directly

Suggested aliases

After you source the plugin, it silently tracks commands you type more than 3 times. Run:

kube-suggest        # prints alias recommendations to stdout
kube-suggest --apply  # writes them to ~/.kube-aliases and sources automatically

Example output:

You've run this 7 times:
  kubectl get pods -n monitoring --sort-by=.metadata.creationTimestamp

Suggested alias:
  alias kgpm='kubectl get pods -n monitoring --sort-by=.metadata.creationTimestamp'

Run `kube-suggest --apply` to add it.

Prod safeguard

Destructive verbs (delete, drain, cordon, scale, rollout restart) against a context matching your configured prod pattern require a confirmation prompt:

⚠️  You are about to run a destructive command against context: prod-eks-ap-south-1

  kubectl delete pod api-server-7d9f4b -n default

Type the context name to confirm: _

If you mistype or press Ctrl+C, the command is blocked and nothing is sent to the cluster.

Audit commands

kube-audit           # show recent audit entries
kube-audit-search delete  # search audit log for specific patterns
kube-audit-stats     # show audit statistics

Context export/import

kexport context <name> [file]     # Export a single context
kexport contexts <pattern> [file] # Export contexts matching pattern
kexport list                       # List exported contexts
kimport <file> [--merge]           # Import context(s) from file

Namespace favorites

kns-fav-add <namespace> [description]  # Add namespace to favorites
kns-fav-remove <namespace>             # Remove namespace from favorites
kns-fav-list                          # List favorite namespaces
kns-fav [namespace]                   # Switch to favorite namespace

Context comparison

kdiff [context1] [context2]  # Compare two contexts or show current vs another
kinfo [context]              # Show detailed context information

Tool integrations

kk9s [context] [namespace]  # Launch K9s with context/namespace
khelm <context> [args]      # Run Helm commands in context
khelm-list [context] [ns]    # List Helm releases
kstern <context> <pattern>   # Tail logs with Stern
ktitle [context] [namespace] # Set VS Code terminal title

Resource management

kquota [namespace]           # Show resource quotas
klimits [namespace]          # Show limit ranges
kpod-res [namespace]         # Show pod resource usage
knode-res                    # Show node resource summary
kpvc [namespace]             # Show PVC usage
kcleanup [namespace] [dry]   # Clean up unused resources
kres-events [ns] [type] [name]  # Show resource events
kimages [namespace]          # Analyze container images
ksec-analysis [namespace]   # Security context analysis

Configuration

Set these in your .bashrc / .zshrc before sourcing the plugin:

# Show context in prompt — set to 0 to disable (default: 1)
export KCM_PROMPT=1

# Prompt style: 'minimal' shows just context name, 'full' shows context:namespace
export KCM_PROMPT_STYLE="full"

# Security: Enable/disable audit logging (default: 1)
export KCM_ENABLE_AUDIT=1

# Security: Enable/disable command analytics (default: 1)
export KCM_ENABLE_ANALYTICS=1

# Security: Enable/disable usage tracking (default: 1)
export KCM_ENABLE_USAGE_TRACKING=1

# Security: Enable/disable caching (default: 1)
export KCM_ENABLE_CACHE=1

# Security: Enable/disable sensitive data redaction (default: 1)
export KCM_REDACT_SENSITIVE_DATA=1

# History & Favorites
export KCM_HISTORY_MAX=20                    # Max history entries
export KCM_FAVORITES_MAX=10                  # Max favorites
export KCM_NS_FAVORITES_MAX=10               # Max namespace favorites

# Safeguard
export KCM_DESTRUCTIVE_VERBS="delete|drain|cordon|scale|rollout.*restart|rollout.*undo|rollout.*abort|apply.*delete|patch|exec|attach"
export KCM_DRY_RUN_MODE=0                    # Enable dry-run by default
export KCM_CONFIRMATION_MODE="strict"        # strict|simple|none

Security

kube-ctx-manager is designed with security as a top priority, especially for cluster environments. All data files are protected with restrictive permissions and sensitive data is automatically redacted.

Security Features

FeatureDescription
Sensitive Data RedactionAutomatically redacts secrets, tokens, passwords, and sensitive patterns from logs and cache
Secure File PermissionsAll data files created with chmod 600 (owner-only), directories with chmod 700
Configurable SecurityEach security feature can be individually enabled/disabled via environment variables
No Data LeaksCommands with sensitive resources (secrets, configmaps) are not cached
Secure by DefaultAll security features enabled by default, following defense-in-depth principles

Sensitive Data Redaction

The plugin automatically redacts the following patterns from all logs and cached data:

  • Secret/configmap/token/password names
  • --from-literal values
  • --token authentication values
  • Base64-encoded credentials (40+ characters)
  • Output format flags (-o yaml/json)

Example redaction:

Before: kubectl get secret db-password -o yaml
After:  kubectl get secret REDACTED -o redacted

Security Configuration

Set these in your .bashrc / .zshrc before sourcing the plugin:

# Enable/disable audit logging (default: 1)
export KCM_ENABLE_AUDIT=1

# Enable/disable command analytics (default: 1)
export KCM_ENABLE_ANALYTICS=1

# Enable/disable command usage tracking for alias suggestions (default: 1)
export KCM_ENABLE_USAGE_TRACKING=1

# Enable/disable caching (default: 1)
export KCM_ENABLE_CACHE=1

# Enable/disable sensitive data redaction (default: 1, not recommended to disable)
export KCM_REDACT_SENSITIVE_DATA=1

# Audit log retention period in days (default: 90)
export KCM_AUDIT_RETENTION_DAYS=90

# Analytics data retention period in days (default: 90)
export KCM_ANALYTICS_RETENTION_DAYS=90

Disabling Security Features

If you need to disable specific security features (not recommended for production):

# Disable audit logging
export KCM_ENABLE_AUDIT=0

# Disable analytics
export KCM_ENABLE_ANALYTICS=0

# Disable usage tracking
export KCM_ENABLE_USAGE_TRACKING=0

# Disable caching
export KCM_ENABLE_CACHE=0

File Permissions

All data files are created with secure permissions:

File/DirectoryPermissionsDescription
~/.kube/audit.log600Audit log file
~/.kube-analytics/700Analytics directory
~/.kube-cache/700Cache directory
~/.kube-usage600Usage tracking file
~/.kube-debug.log600Debug log file
~/.kube-bookmarks600Bookmarks file
~/.kube-ctx-manager/700Configuration directory

Security Best Practices

  1. Never disable data redaction in production environments
  2. Review audit logs regularly for suspicious activity
  3. Set appropriate retention periods based on your compliance requirements
  4. Restrict access to ~/.kube/ directory on multi-user systems
  5. Keep the plugin updated to get security patches

Cluster Deployment

When deploying in a cluster environment:

  • All security features are enabled by default
  • No sensitive data is logged or cached
  • Files are created with restrictive permissions (600/700)
  • The plugin runs entirely within the user's shell session (no background processes)

Development

# Run tests (requires bats-core)
brew install bats-core
bats tests/

# Lint
shellcheck lib/*.sh

# Test locally
source ./kube-ctx-manager.bash  # or .zsh for Zsh
kx

Running tests

# Install test dependencies
brew install bats-core

# Run all tests
bats tests/

# Run specific test file
bats tests/test_context.sh

# Run with verbose output
bats -t tests/

Contributing

  1. Fork the repository
  2. Create a feature branch
  3. Make your changes
  4. Add tests for new functionality
  5. Run shellcheck lib/*.sh and fix any issues
  6. Run bats tests/ and ensure all tests pass
  7. Submit a pull request

Roadmap

  • Multi-kubeconfig merging helper (kube-merge)
  • VS Code terminal integration (context badge in title bar)
  • Helm release context awareness
  • K9s integration
  • Homebrew tap for one-command install
  • Fish shell support
  • Team-shared alias sync via a dotfiles-compatible format
  • Context health checks and auto-failover

Troubleshooting

Common Issues

Plugin not loading

  • Ensure you've sourced the plugin in your shell config
  • Restart your terminal or run source ~/.bashrc / source ~/.zshrc

fzf not found

  • Install fzf: brew install fzf or git clone --depth 1 https://github.com/junegunn/fzf.git ~/.fzf && ~/.fzf/install

kubectl not found

Aliases not being suggested

  • Check your usage threshold: echo $KCM_SUGGEST_THRESHOLD
  • Verify tracking file exists: ls -la ~/.kube-usage

Prod safeguard not working

  • Check your prod pattern: echo $KCM_PROD_PATTERN
  • Verify current context matches pattern: kubectl config current-context

Debug Mode

Enable debug output by setting:

export KCM_DEBUG=1

This will show additional information about plugin operations.


License

MIT License - see LICENSE file for details.


Credits

Inspired by various kubectl context management tools, but focused on being a lightweight, non-intrusive shell plugin that works out of the box.


Support