Skip to content

NotHarshhaa/kube-ctx-manager

Repository files navigation

kube-ctx-manager

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

Feature What it does
Fuzzy context switcher kx opens an fzf picker across all your kubeconfig contexts
Alias suggester Watches your kubectl usage and suggests aliases for long commands you repeat
Prod safeguard Any destructive command against a prod/production/live context requires explicit confirmation
Namespace switcher kns fuzzy-picks namespaces within the current context
Context label Injects current context + namespace into your shell prompt (PS1/RPROMPT)
Audit log Every kubectl command against a prod context is appended to ~/.kube/audit.log
Health monitoring khealth checks cluster connectivity and response times
Kubeconfig merging kube-merge combines multiple kubeconfig files safely
Backup & restore kube-backup creates and restores kubeconfig backups
Advanced search ksearch finds contexts by name, cluster, user, or pattern
Context bookmarks kbookmark saves favorite contexts with descriptions
Resource monitoring kmonitor shows cluster resource usage and health
Command analytics kanalytics tracks usage patterns and generates reports
Security features Sensitive data redaction, secure file permissions, configurable security options

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

One-liner (recommended)

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
```ackup
ps
 i
kube-split                # Split kubeconfig by patterns
`  imUDIT_LOG="$HOME/.kube/audit.log"

# 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

# 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

Feature Description
Sensitive Data Redaction Automatically redacts secrets, tokens, passwords, and sensitive patterns from logs and cache
Secure File Permissions All data files created with chmod 600 (owner-only), directories with chmod 700
Configurable Security Each security feature can be individually enabled/disabled via environment variables
No Data Leaks Commands with sensitive resources (secrets, configmaps) are not cached
Secure by Default All 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/Directory Permissions Description
~/.kube/audit.log 600 Audit log file
~/.kube-analytics/ 700 Analytics directory
~/.kube-cache/ 700 Cache directory
~/.kube-usage 600 Usage tracking file
~/.kube-debug.log 600 Debug log file
~/.kube-bookmarks 600 Bookmarks file
~/.kube-ctx-manager/ 700 Configuration 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)

Repo structure

kube-ctx-manager/
├── kube-ctx-manager.plugin.zsh   # Main plugin (Zsh entry point)
├── kube-ctx-manager.bash         # Bash entry point
├── lib/
│   ├── context.sh                # kx and kns logic
│   ├── safeguard.sh              # Prod confirmation wrapper
│   ├── suggester.sh              # Alias usage tracking and suggestions
│   ├── prompt.sh                 # PS1/RPROMPT injection
│   ├── audit.sh                  # Audit logging
│   ├── health.sh                 # Health monitoring
│   ├── merge.sh                  # Kubeconfig merging
│   ├── backup.sh                 # Backup and restore
│   ├── search.sh                 # Advanced search
│   ├── bookmarks.sh              # Context bookmarks
│   ├── monitor.sh                # Resource monitoring
│   └── analytics.sh              # Command analytics
├── install.sh                    # Installer script
├── uninstall.sh                  # Clean removal
├── tests/
│   ├── test_context.sh
│   ├── test_safeguard.sh
│   ├── test_suggester.sh
│   └── test_helper.bash
└── README.md

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

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

Troubleshooting

Common Issues

Plugin not loading

  • En├ure you've sourced the plugin in your shell config │ - Rehsstory.sh # Cottext hiatory and favorires │ ├── quick.sh # Quick resource tctions │ ├── groups.sh # Context groups │ └── templates.sh # Command temp ates ├── instaylour 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.


Supt pests/


### Contributing

1. Fork the repository
2. Create a feature branch
3. Make your changes
4. Addort 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

- [ ] Homebrew tap for one-command install
- [ ] Fish shell support
- [ ] Multi-kubeconfig merging helper (kube-merge`)
- [ ] Team-shared alias sync via a dotfiles-compatible format
- [ ] VS Code terminal integration (context badge in title bar)
- [ ] Helm release context awareness
- [ ] K9s integration
- [ ] 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**
- Install kubectl: `brew install kubectl` or follow the [official installation guide](https://kubernetes.io/docs/tasks/tools/)

**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:

```bash
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

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

  • Homebrew tap for one-command install
  • Fish shell support
  • Multi-kubeconfig merging helper (kube-merge)
  • Team-shared alias sync via a dotfiles-compatible format
  • VS Code terminal integration (context badge in title bar)
  • Helm release context awareness
  • K9s integration
  • 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

Support

About

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

Topics

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages