GithubHelp home page GithubHelp logo

danielfoehrkn / kubeswitch Goto Github PK

View Code? Open in Web Editor NEW
766.0 7.0 72.0 182.71 MB

The kubectx for operators.

Home Page: https://danielfoehrkn.medium.com/the-case-of-kubeswitch-aff4b6a04ae7

License: Apache License 2.0

Makefile 1.54% Shell 1.38% Go 97.09%
kubectx kubeconfig kubecontext kubernetes kubeswitch

kubeswitch's Introduction

Kubeswitch

Latest GitHub release Build Go Report Card License

The kubectx for operators.

kubeswitch (lazy: switch) is the single pane of glass for all of your kubeconfig files.
Caters to operators of large scale Kubernetes installations. Designed as a drop-in replacement for kubectx.

Highlights

  • Unified search over multiple providers
  • Change the namespace
  • Change to any context and namespace from the history
  • Terminal Window Isolation
    • Each terminal window can target a different cluster (does not overwrite the current-context in a shared Kubeconfig)
    • Each terminal window can target the same cluster and set a different namespace preference
  • Efficiency: uses local caches for kubeconfig contexts and namespaces
  • Advanced Search Capabilities
    • Hot reload capability (adds Kubeconfigs to the search on the fly - especially useful when searching large directories)
    • Live preview of the selected Kubeconfig file (sanitized from credentials)
    • Recursive search (e.g. on the local filesystem or in Vault)
    • Easily find clusters with cryptic context names
  • Easy Navigation
    • Define alias names for contexts without changing the underlying Kubeconfig
  • Extensibility
    • Integrate custom functionality using Hooks (comparable with Git pre-commit hooks).
    • Build your own integration e.g., synchronise Kubeconfig files of clusters from Git or remote systems.

demo GIF

Non-goals

  • To provide a customized shell prompt. Use kube-ps1.

Installation

Kubeswitch can be installed using brew for OSX, MacPorts, from Github Releases or from source. Please see the documentation.

Usage

$ switch -h
The kubectx for operators.

Usage:
  switch [flags]
  switch [command]

Available Commands:
  alias                Create an alias for a context. Use ALIAS=CONTEXT_NAME
  clean                Cleans all temporary and cached kubeconfig files
  completion           Generate the autocompletion script for the specified shell
  exec                 Execute any command towards the matching contexts from the wildcard search
  gardener             gardener specific commands
  help                 Help about any command
  history              Switch to any previous tuple {context,namespace} from the history
  hooks                Run configured hooks
  list-contexts        List all available contexts
  namespace            Change the current namespace
  set-context          Switch to context name provided as first argument
  set-last-context     Switch to the last used context from the history
  set-previous-context Switch to the previous context from the history
  version              show switch version info

Flags:
      --config-path string         path on the local filesystem to the configuration file. (default "/Users/tommyolsen/.kube/switch-config.yaml")
      --debug                      show debug logs
  -h, --help                       help for switch
      --kubeconfig-name string     only shows kubeconfig files with this name. Accepts wilcard arguments '*' and '?'. Defaults to 'config'. (default "config")
      --kubeconfig-path string     path to be recursively searched for kubeconfigs. Can be a file or a directory on the local filesystem or a path in Vault. (default "$HOME/.kube/config")
      --no-index                   stores do not read from index files. The index is refreshed.
      --show-preview               show preview of the selected kubeconfig. Possibly makes sense to disable when using vault as the kubeconfig store to prevent excessive requests against the API. (default true)
      --state-directory string     path to the local directory used for storing internal state. (default "/Users/tommyolsen/.kube/switch-state")
      --store string               the backing store to be searched for kubeconfig files. Can be either "filesystem" or "vault" (default "filesystem")
      --vault-api-address string   the API address of the Vault store. Overrides the default "vaultAPIAddress" field in the SwitchConfig. This flag is overridden by the environment variable "VAULT_ADDR".
  -v, --version                    version for switch

Use "switch [command] --help" for more information about a command.

Just type switch to search over the context names defined in the default Kubeconfig file ~/.kube/config or from the environment variable KUBECONFIG.

To recursively search over multiple directories, files and Kubeconfig stores, please see the documentation to set up the necessary configuration file.

Change namespace

Change the current namespace using switch ns Uses a self-updating local namespace cache for instant search results.

History

Similar to the command histories of a shell, switch keeps a history of used contexts and namespaces. A history entry is always a tuple of {context-name, namespace}. This allows to jump back to any context and namespace in the history.

In addition, use

  • switch . to change to the last used context and namespace (handy for new terminals)
  • switch - to change to the previous history entry

List and search for contexts

You can list all your indexed contexts by issuing the following command: switch list-contexts. And if you want to search for only parts of those contexts, you can use wildcard search:

switch list-contexts "*-dev-?"

Wildcard search supports matching wildcards notation also known as globbing:

  • ? matches exactly one occurrence of any character.
  • * matches arbitrary many (including zero) occurrences of any character.

Execute commands

You can use the above wildcard search to execute any commands towards the matching clusters. This makes it powerful for quickly running a command through a given set of clusters and see the output of these commands:

switch exec "*-dev-?" -- kubectl get ns

You can also wrap the command(s) into a script and execute it via switch exec:

switch exec "*-dev-?" -- bash script.sh

For inline shell script execution, you need to specify the default shell in the SwitchConfig file:

# ~/.kube/switch-config.yaml
kind: SwitchConfig
execShell: "/bin/bash"

Then you can run shell commands like so:

# executes /bin/bash -c 'for i in 1 2 3; do sleep 1; echo "hi $i"; done'
switch exec "*-dev-?" -- 'for i in 1 2 3; do sleep 1; echo "hi $i"; done'

Kubeconfig stores

Multiple Kubeconfig stores are supported. The local filesystem is the default store and does not require any additional setup. However, if you intend to search for all Kubeconfig context/files in the ~/.kube directory, please first consider this.

To search over multiple directories and setup Kubeconfig stores (such as Vault), please see here.

Kubeconfig cache

A cache for kubeconfig files can be added to a store to prevent loading from remote on each invocation of kubeswitch. The kubeconfig file will be cached after first download.

To see how to configure the cache, please see here.

Transition from Kubectx

Offers a smooth transition as kubeswitch is a drop-in replacement for kubectx. You can set an alias and keep using your existing setup.

  alias kubectx='switch'
  alias kctx='switch'

However, that does not mean that kubeswitch behaves exactly like kubectx. Please see here to read about some main differences to kubectx.

Alias

An alias for any context name can be defined. An alias does not modify or rename the context in the kubeconfig file, instead it is just injected for the search.

Define an alias.

$ switch alias mediathekview=gke_mediathekviewmobile-real_europe-west1-c_mediathekviewmobile

It is also possible to use switch alias <alias>=. to create an alias for the current context.

See the created alias

$ switch alias ls
+---------------+-------------------------------------------------------------------------------+
| ALIAS         | CONTEXT                                                                       |
+---------------+-------------------------------------------------------------------------------+
| mediathekview | mediathekview/gke_mediathekviewmobile-real_europe-west1-c_mediathekviewmobile |
+---------------+-------------------------------------------------------------------------------+
| TOTAL         | 1                                                                             |
+---------------+-------------------------------------------------------------------------------+ 

Remove the alias

$ switch alias rm mediathekview

Caching

See here how to use a search index (cache) to speed up search operations. Using the search index is especially useful when

  • dealing with large amounts of Kubeconfigs and querying the Kubeconfig store is slow (e.g. searching a large directory)
  • when using a remote systems (such as Vault) as the Kubeconfig store to increase search speed, reduce latency and save API requests

Hot Reload

For large directories with many Kubeconfig files, the Kubeconfigs are added to the search set on the fly. For smaller directory sizes, the search feels instantaneous.

demo GIF

Search cryptic context names

Unfortunately operators sometimes have to deal with cryptic or generated kubeconfig context names that make it hard to guess which Kubernetes cluster this kubeconfig context actually points to. For example, these could be temporary CI clusters.

Without having to manually change the Kubeconfig file, kubeswitch makes it easier to identify the right context name by including the direct parent path name in the fuzzy search. This way, the directory layout can actually convey information useful for the search.

To exemplify this, look at the path layout below. Each Kubernetes landscape (called dev, canary and live) have their own directory containing the Kubeconfigs of the Kubernetes clusters on that landscape. Every Kubeconfig is named config.

$ tree .kube/my-path
.kube/my-path
├── canary
│   └── config
├── dev
│   ├── config
│   └── config-tmp
└── live
    └── config

This is how the search looks like for this directory. The parent directory name is part of the search.

demo GIF

You can either manually create such a path layout and place the kubeconfigs, or write a custom hook (script / binary) to do that prior to the search.

Extensibilty

Customization is possible by using Hooks (think Git pre-commit hooks). Hooks can call an arbitrary executable or execute commands at a certain time (e.g every 6 hours) prior to the search via kubeswitch. For more information take a look here.

Difference to kubectx

kubectx is great when dealing with few Kubeconfig files - however lacks support when operating large Kubernetes installations where clusters spin up on demand, have cryptic context names or are stored in various kubeconfig stores (e.g., Vault).

kubeswitch is build for a world where Kubernetes clusters are treated as cattle, not pets. This has implications on how Kubeconfig files are managed. kubeswitch is fundamentally designed for the modern Kubernetes operator of large dynamic Kubernetes installations with possibly thousands of Kubeconfig files in various locations.

Has build-in

  • convenience features (terminal window isolation, context history, context aliasing, improved search experience, sanitized Kubeconfig preview);
  • advanced search capabilities (search index, hot reload);
  • as well as integration points with external systems (hooks).

In addition, kubeswitch is a drop-in replacement for kubectx. You can set an alias and keep using your existing setup.

  alias kubectx='switch'
  alias kctx='switch'

However, that does not mean that kubeswitch behaves exactly like kubectx.

Alias Names

kubectx supports renaming context names using kubectx <NEW_NAME>=<NAME>. Likewise, use switch <NEW_NAME>=<NAME> to create an alias. An alias does not modify or rename the context in the kubeconfig file. It is just a local configuration that can be removed again via switch alias rm <NAME>. Directly modifying the Kubeconfig is problematic:

  • Common tooling might be used across the team which needs to rely on predictable cluster naming conventions
  • Modifying the file is not always possible e.g., when the Kubeconfig is actually stored in a Vault
  • No easy way to revert the alias or see aliases that are currently in use

Terminal Window isolation

kubectx directly modifies the kubeconfig file to set the current context. This has the disadvantage that every other terminal using the same Kubeconfig file (e.g, via environment variable KUBECONFIG) will also be affected and change the context.

A guideline of kubeswitch is to not modify the underlying Kubeconfig file. Hence, a temporary copy of the original Kubeconfig file is created and used to modify the context. This way, each terminal window works on its own copy of the Kubeconfig file and cannot interfere with each other.

Limitations

Please make sure there are no kubeconfig files that have the same context name within one directory. Define multiple search paths using the configuration file.

Future Plans

  • Support more Cloud Providers and Managed Kubernetes Platforms

kubeswitch's People

Contributors

antigenius0910 avatar averagemarcus avatar blzgjariv avatar croissong avatar danielfoehrkn avatar dependabot[bot] avatar digitaloceandaniel avatar druesendieb avatar fmengue avatar gaetanars avatar guillaumebernardfgtech avatar herbygillot avatar joemiller avatar johnvanhienen avatar kbudde avatar kluen avatar landerz123 avatar meroje avatar nobbs avatar pblgomez avatar posquit0 avatar restanrm avatar rothgar avatar shoekstra avatar sncf-ttc avatar tedteng avatar tomasaschan avatar tommy-dk avatar watcherwhale avatar zebradil avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar

kubeswitch's Issues

arm64 images for Homebrew

I just tried to install on my M1 Mac and received switcher: The x86_64 architecture is required for this software.

I checked the releases and found an arm64 version. Could you make that available via Homebrew?

help information is misunderstanding

i tried switch namespace default, it didn't work. Error: context with name "default" not found. i searched the issues list, found i'd use switch ns

The kubectx for operators.

Usage:
switch [flags]
switch [command]

Available Commands:
alias Create an alias for a context. Use ALIAS=CONTEXT_NAME
clean Cleans all temporary kubeconfig files
completion Generate the autocompletion script for the specified shell
gardener gardener specific commands
help Help about any command
history Switch to any previous tuple {context,namespace} from the history
hooks Run configured hooks
list-contexts List all available contexts without fuzzy search
namespace Change the current namespace
set-context Switch to context name provided as first argument
set-last-context Switch to the last used context from the history
set-previous-context Switch to the previous context from the history
version show Switch Version info

Flags:
--config-path string path on the local filesystem to the configuration file. (default "/Users/d060239/.kube/switch-config.yaml")
--debug show debug logs
-h, --help help for switch
--kubeconfig-name string only shows kubeconfig files with this name. Accepts wilcard arguments "*" and "?". Defaults to "config". (default "config")
--kubeconfig-path string path to be recursively searched for kubeconfigs. Can be a file or a directory on the local filesystem or a path in Vault. (default "$HOME/.kube/config")
--no-index stores do not read from index files. The index is refreshed.
--show-preview show preview of the selected kubeconfig. Possibly makes sense to disable when using vault as the kubeconfig store to prevent excessive requests against the API. (default true)
--state-directory string path to the local directory used for storing internal state. (default "/Users/d060239/.kube/switch-state")
--store string the backing store to be searched for kubeconfig files. Can be either "filesystem" or "vault" (default "filesystem")
--vault-api-address string the API address of the Vault store. Overrides the default "vaultAPIAddress" field in the SwitchConfig. This flag is overridden by the environment variable "VAULT_ADDR".
-v, --version version for switch

warning when switching contexts

Every time I switch my shell from one context to another I get a warning to remove the tempfile... seems like overkill or something I'd like to opt out of. I thought it was because I have alias rm='rm -i' but I removed the alias and it still happens so I guess kubeswitch is implementing that confirmation itself.

$ switch
switched to context "foo".
$ switch
remove /Users/michael/.kube/.switch_tmp/config.2360448475.tmp? y
switched to context "bar".

It's probably also worth pointing out that if I select n then it claims it worked anyway - looks like tmp files are just accumulating in ~/.kube/.switch_tmp.

option to overwrite `current-context`

Instead of replacing the KUBECONFIG with a dynamically created config, sometimes I want to explicitly set the current-context in my existing KUBECONFIG. This would make a nice CLI option. Maybe something like switch --set-current-context or switch --keep-kubeconfig

do not lose the KUBECONFIG environment variable when clobbering it

So I've always maintained a custom KUBECONFIG=$HOME/.kube/config:$HOME/.kube/foo:$HOME/.kube/bar. This works great for kubeswitch on the first time I run it - and then it overwrites the env var with its custom tempfile. The second time I run kubeswitch the values are lost, and only the default $HOME/.kube/config file is shown as options of context's to switch to. I would expect it to save the KUBECONFIG value somewhere and on subsequent invocations show me all of those options.

Alternatively I can define switch-config.yaml and maintain it separately but then of course I have it maintained in two locations when I'd prefer to use the "standard" support in kubectl in some situations.

PS thanks for this tool - it scratches an itch I've had for a really long time and you've done a much nicer job implementing it than anything I was thinking to do for myself!

Support for / ignore comma separated KUBECONFIG env paths

Hello,

The Kubernetes documentation states that a colon separated list of paths is supported for the KUBECONFIG environment variable :

https://kubernetes.io/docs/tasks/access-application-cluster/configure-access-multiple-clusters/#linux

However kubeswitch seems to have trouble with this :

% echo $KUBECONFIG
/home/alex/.kube/configs/first.config:/home/alex/.kube/configs/second.config
% switch
Error: the configured kubeconfig directory "/home/alex/.kube/configs/first.config:/home/alex/.kube/configs/second.config" does not exist
the configured kubeconfig directory "/home/alex/.kube/configs/first.config:/home/alex/.kube/configs/second.config" does not exist

Am I doing something wrong?

Cheers,

Alexander

Doesn't switch

I started to test this from one of the first releases but have the same issue each time.
Execute switcher, expect that it had changed the context but it don't.

switcher --debug
DEBU[0000] Using kubeconfig path from flag /home/user/.kube/config 
DEBU[0000] Starting search for store: filesystem         store=filesystem
DEBU[0000] GetKubeconfigForPath: /home/user/.kube/config not cached  store=filesystem
DEBU[0002] GetKubeconfigForPath: /home/user/.kube/config found in cache  store=filesystem
/home/user/.kube/.switch_tmp/config.52797184.tmp

In this tmp file the current-context key has right value, the one that I selected.

switch version v0.7.2
bash 5.1.4(1)-release
context source: ~/.kube/config
Debian GNU/Linux 11 (bullseye)

Gardener Store: obtain CA secret from caCluster.Secret instead of <shoot-name>.kubeconfig

This is important, as the gardenlogin-controller is deprecated. In the past, this controller created the Shoot kubeconfig via the ShootState as a <shoot-name>.kubeconfig config map in the project ns in the garden.

  • This extension is deperecated and will be removed from landscapes in the future
  • The current controller does not update the config map after a Shoot CA rotation

For more information, please see here: https://github.com/gardener/gardenctl-v2/pull/149/files#

"switch completion" command does not work

Hi guys, thank you for this great tool.
Unfortunately there is a bug in the command shell completion.

Here what happens:

$ switch completion
Error: context with name "completion" not found

I installed kubeswitch using homebrew, then sourced the switch.sh as described in the docs:

$ INSTALLATION_PATH=$(brew --prefix switch) && source $INSTALLATION_PATH/switch.sh

Here the version:

$ switch -v
Switch:
		version     : v0.7.1
		build date  : 2022-06-22
		go version  : go1.18.3
		go compiler : gc
		platform    : darwin/amd64

Here shell info:

$ zsh --version
zsh 5.9 (x86_64-apple-darwin21.3.0)

It would be great to have this command working, so instead of being forced to manually download an additional file (scripts/_switch.bash) we could source that directly in .zshrc/.bashrc/.bash_profile

Provide LICENSE file

Hi there!

Thanks for the awesome project!

Just to make it clear, would be nice to have the LICENSE file, so far I only know from a quick look that the project is Apache 2 because of the little badge in the README.md.

Thanks!

not scanning kubeconfigs and --kubeconfig-directory option not working

Running as readme suggests only shows help output ?

$ switch --kubeconfig-directory ~/.kube

Simple tool for switching between kubeconfig contexts. The kubectx build for people with a lot of kubeconfigs.

Usage:
  switch [flags]
  switch [command]

Available Commands:
  clean       Cleans all temporary kubeconfig files
  help        Help about any command
  hooks       Runs configured hooks

Flags:
      --config-directory string    path to the configuration file. (default "~/.kube/switch-config.yaml")
  -h, --help                       help for switch
      --kubeconfig-name string     only shows kubeconfig files with this name. Accepts wilcard arguments "*" and "?". Defaults to "config". \(default "config")
      --kubeconfig-path string     path to be recursively searched for kubeconfig files. Can be a directory on the local filesystem or a path in Vault. (default "~/.kube")
      --show-preview               show preview of the selected kubeconfig. Possibly makes sense to disable when using vault as the kubeconfig store to prevent excessive requests against the API. (default true)
      --state-directory string     path to the local directory used for storing internal state. (default "~/.kube/switch-state")
      --store string               the backing store to be searched for kubeconfig files. Can be either "filesystem" or "vault" (default "filesystem")
      --vault-api-address string   the API address of the Vault store.

Use "switch [command] --help" for more information about a command.

That folder contains:

$ ls ~/.kube 
7ejidqmfi9-k8sca  cache  http-cache  kubectx  kubens  microk8s  p-boa-kube-ca  switch-config.yaml  t-boss-ca

and if I run switch with no arguments.. it just says 0/0 at the bottom.. Nothing to choose from :(

Suggestion: create a krew installer

Hi! Nice project! HAve you considered creating a krew installer?

Like the one for ctx.
It makes everything more linear from an user perspective and also help the project to grow working like advertising.

EDIT: missing info

Rancher: Create expiring tokens

It seems when using switch with Rancher that the scoped tokens that get created don't have an expiry date. It would be a nice security property to have switch create token with let's say a day of validity since it can create new ones with the bearer token anyway.

This way one could create a bearer token that lasts for a month or a year and protect that one especially and at the same time have kind of temporary credentials be created and used by switch that, if compromised, expire very fast by themself.

I'm curious what other might think about that proposal.

PS: Thanks for the awesome tool, it makes my daily work so much easier! 🙇

Add flag that disables cache

Add a flag that allows disabling of the cache per command.
Currently, there is only one global configuration in the switch config file.

Error saving history when switching context

Hello, I'm testing the latest kubeswitch on my Mac

$ switcher version
Switch:
		version     : v0.6.0
		build date  : 2021-12-13
		go version  : go1.17.4
		go compiler : gc
		platform    : darwin/amd64

when I try to run the interactive interface to select the context to switch to, I've got the following error:

$ switcher --debug
DEBU[0000] Using kubeconfig path from flag /Users/myuser/.kube/config 
DEBU[0000] Added store with kind filesystem and ID filesystem.env-and-flag 
WARN[0006] failed to append context to history file: cannot open file: open /Users/myuser/.kube/.switch_history: no such file or directory 
/Users/myuser/.kube/.switch_tmp/config.122399507.tmp

the interactive screen works fine, I see the list of contexts just fine and I can select the new context just fine, but when I hit enter the set the context, the error above shows up.

If I create an empty /Users/myuser/.kube/.switch_history file, then I get a different error message:

$ touch /Users/myuser/.kube/.switch_history
crmar@crmac10-lp Documents $ switcher --debug
DEBU[0000] Using kubeconfig path from flag /Users/myuser/.kube/config 
DEBU[0000] Added store with kind filesystem and ID filesystem.env-and-flag 
WARN[0003] failed to append context to history file: seek /Users/myuser/.kube/.switch_history: invalid argument 
/Users/myuser/.kube/.switch_tmp/config.1892608840.tmp

This is the very first time I run kubeswitch, then I guess not having the .switch_history file is expected in that case.

any ideas ?

Kubeswitch does not switch kubeconfig on selection

I'm using kube-ps1 in order to show what cluster I'm connected to in my PS1 prompt. However, when I use kubeswitch/switcher to switch. I get no error. But the PS1 prompt does NOT change as well as a test with kubectl get nodes verifies that I still see the nodes from the cluster I'm trying to switch away from.

  • I'm on v0.3.0 of kubeswitch
  • I'm running kubectx and kubens at the same time. Is that a problem?

Looking forward to hear from you and thank you

Supports Vault KV v2?

I can't seem to get switcher to work with my KV v2 secret store. Is v2 supported?

$ switcher --debug
DEBU[0000] Using kubeconfig path from flag /Users/blah/.kube/config
DEBU[0000] Added store with kind vault and ID vault.default
DEBU[0000] Added store with kind filesystem and ID filesystem.env-and-flag
WARN[0001] Supressed warnings during the search: 1 error occurred:
	* store "vault.default" returned an error during the search: Error making API request.

URL: GET https://vault.blabla.net/v1/platform-kv/data/kubernetes?list=true
Code: 405. Errors:

* 1 error occurred:
	* unsupported operation



Error: abort
abort%

Question: kubeswitch print only shortened context name?

Hi,

is that only me or is kubeswitch using any shortened context name?

Here an example:

$ kubectx | grep windows-workload                                             <===== Original kubectx 
windows-workload/api-vmw-stormshift-coe-muc-redhat-com:6443/kube:admin
$ grep -B4 'windows-workload/' ~/.kube/config
  - context:
        cluster: api-vmw-stormshift-coe-muc-redhat-com:6443
        namespace: windows-workload
        user: kube:admin/api-vmw-stormshift-coe-muc-redhat-com:6443
    name: windows-workload/api-vmw-stormshift-coe-muc-redhat-com:6443/kube:admin
$ switch list-contexts  | grep windows
$ switch list-contexts  | grep kube:admin
.kube/kube:admin
.kube/kube:admin
.kube/kube:admin
.kube/kube:admin
.kube/kube:admin
.kube/kube:admin
.kube/kube:admin
.kube/kube:admin
.kube/kube:admin
.kube/kube:admin
.kube/kube:admin
.kube/kube:admin
.kube/kube:admin
.kube/kube:admin
.kube/kube:admin
.kube/kube:admin
.kube/kube:admin
.kube/kube:admin
.kube/kube:admin
.kube/kube:admin
.kube/kube:admin
.kube/kube:admin
$

my switch configuration

kind: SwitchConfig
version: v1alpha1
kubeconfigStores:
- kind: filesystem
  paths:
  - ~/.kube/config

switch version

$ switch version
Switch:
		version     : v0.4.1
		build date  : 2021-03-16
		go version  : go1.15.8
		go compiler : gc
		platform    : linux/amd64

I would like to see the whole context name.

Thanks for any advice
Cheers
Robert

Invalid value: "rancher": kind "rancher" of kubeconfig store is unknown

I have installed switch from Homebrew, and when using example Rancher store config I get this error:

Error: the switch configuration file contains errors: kubeconfigStores[0].kind: Invalid value: "rancher": kind "rancher" of kubeconfig store is unknown. Valid kinds are map["azure":{} "eks":{} "filesystem":{} "gardener":{} "gke":{} "vault":{}]

brew info:

❯ brew info switch
Warning: Treating switch as a formula. For the cask, use homebrew/cask/switch
==> danielfoehrkn/switch/switch: stable 0.7.1
The kubectx for operators.
https://github.com/danielfoehrKn/kubeswitch
/opt/homebrew/Cellar/switch/0.7.1 (3 files, 17.7KB) *
  Built from source on 2022-09-20 at 13:17:10
From: https://github.com/danielfoehrkn/homebrew-switch/blob/HEAD/switch.rb
==> Dependencies
Required: danielfoehrkn/switch/switcher ✔

Sort available contexts list

Hi!

Thanks for this tool - I only started using it but it looks very promising so far!

I was not able to find a way to get my list of available contexts appear sorted though. I mean mainly the output of switch (for switch list-contexts I would just pipe it to sort, but I don't need that). Is it possible to make this list sorted?

Gardener landscape not working after 0.6 release

Hi Daniel,

I'm struggling to make switcher load Gardener landscape(s) after 0.6 release. I'm aware of the new AdminKubeconfigRequest, which I have enabled at apiserver. I also tested the functionality of AdminKubeconfigRequest via creating the request manually and also via gardenlogin kubeconfig which also works.
When I downgrade back to 0.5 then gardener landscape load correctly.
Only extra output I get, when running switch with debug.

switcher --debug --no-index --show-preview=false
DEBU[0000] Using kubeconfig path from flag /Users/..../.kube/config
DEBU[0000] Added store with kind gardener and ID gardener.garden-.....
DEBU[0000] Added store with kind filesystem and ID filesystem.env-and-flag

which seem to me be that gardener being added correctly

any hint would be great

many thanks
Pavel

Direnv support

Hi,

I'm currently using direnv to automatically set the kubeconfig context when entering a directory. This works by exporting KUBECONFIG with direnv.
However, afaik this is not possible with kubeswitch because kubeswitch generates tmp config files like ~/.kube/.switch_tmp/config.1692710140.tmp which don't contain the context name (and are eventually garbage collected ?). It would be nice if kubeswitch would create/update kubeconfig files including at least the name of the context and can be used permanently.
I wonder if such feature is in the scope of kubeswitch.

This is how other projects relate to this issue:

  • kubesess i.e. uses KUBECONFIG=~/.kube/kubesess/cache/mastodon-dev:/home/varac/.kube/config but don't have hook support
  • kubie has a pending PR which adds an export function that can get used with direnv

Possibility to set default context for all new terminals

Hi,

I would like to ask if there is any plan to implement a possibility to set a default context for all future terminals.

Maybe something like:

$ switch --set-default
$ switch some-context --set-default

Currently the workaround for me is to type into every new terminal the following:

$ switch -

Consider renaming the binary

switch is a pretty common term, which may clash with other programs (e.g. fish shell provides switch as a shell builtin).

I think it's better to use the repo name kubeswitch as the binary name. It seems more unified and kubeswitch is a unique enough term on its own.

Suggestion: Select namespace from context list

It would be very useful to be able to select a namespace when selecting a context.

There are 2 ways this could be implemented:

  1. Immediately after selecting the context, it shows the namespace selector list.
  2. Pressing right arrow key on the selected context could switch to the namespace selector list. This preserves existing functionality while allowing the namespace selector to be optional.

Is this something you would consider?

Fail to brew install k8ctx

$ brew -v
Homebrew 3.0.3
Homebrew/homebrew-core (git revision dc577d; last commit 2021-03-01)

Fail to install k8ctx via Homebrew:

$ brew install danielfoehrkn/k8ctx/k8ctx

==> Tapping danielfoehrkn/k8ctx
Cloning into '/usr/local/Homebrew/Library/Taps/danielfoehrkn/homebrew-k8ctx'...
ERROR: Repository not found.
fatal: Could not read from remote repository.

Please make sure you have the correct access rights
and the repository exists.
Error: Failure while executing; `git clone https://github.com/danielfoehrkn/homebrew-k8ctx /usr/local/Homebrew/Library/Taps/danielfoehrkn/homebrew-k8ctx --origin=origin` exited with 128.

kubeconfigs not read?

Running as readme suggests only shows help output ?

$ switch --kubeconfig-directory ~/.kube

Simple tool for switching between kubeconfig contexts. The kubectx build for people with a lot of kubeconfigs.

Usage:
  switch [flags]
  switch [command]

Available Commands:
  clean       Cleans all temporary kubeconfig files
  help        Help about any command
  hooks       Runs configured hooks

Flags:
      --config-directory string    path to the configuration file. (default "~/.kube/switch-config.yaml")
  -h, --help                       help for switch
      --kubeconfig-name string     only shows kubeconfig files with this name. Accepts wilcard arguments "*" and "?". Defaults to "config". \(default "config")
      --kubeconfig-path string     path to be recursively searched for kubeconfig files. Can be a directory on the local filesystem or a path in Vault. (default "~/.kube")
      --show-preview               show preview of the selected kubeconfig. Possibly makes sense to disable when using vault as the kubeconfig store to prevent excessive requests against the API. (default true)
      --state-directory string     path to the local directory used for storing internal state. (default "~/.kube/switch-state")
      --store string               the backing store to be searched for kubeconfig files. Can be either "filesystem" or "vault" (default "filesystem")
      --vault-api-address string   the API address of the Vault store.

Use "switch [command] --help" for more information about a command.

That folder contains:

$ ls ~/.kube 
7ejidqmfi9-k8sca  cache  http-cache  kubectx  kubens  microk8s  p-boa-kube-ca  switch-config.yaml  t-boss-ca

and if I run switch with no arguments.. it just says 0/0 at the bottom.. Nothing to choose from :(

Support namespace switching

  • namespaces cached per context. Requests in the background for hot reload.
  • History of context/namespace combination
  • default namespace (like alias, not set in original kubeconfig as this is not possible for non-local stores)
  • switch to current and previous namespace (like for context)

Switch ns throws error stating kubeconfig file doesn't exist

I tried this wonderful tool. This has become everyday handy tool to switch between clusters/kubeconfigs.

But switching ns doesn't work properly

switch ns
Error: unable to list namespaces. The kubeconfig file "" does not exist
unable to list namespaces. The kubeconfig file "" does not exist%

Error: failed to get namespace of current context: context with name "/Users/userid/.kube/config" not found

echo $SHELL
/bin/zsh

switcher version
Switch:
		version     : v0.6.0
		build date  : 2021-12-15
		go version  : go1.17.4
		go compiler : gc
		platform    : darwin/amd6

switch gke_foo-europe-west1
Error: failed to get namespace of current context: context with name "/Users/userid/.kube/config" not found
grep context -A1 /Users/userid/.kube/config
contexts:
- context:
    cluster: gke_foo-europe-west1
--

when I run only switch, the context is listed without issue.

What I'm doing wrong ?

Allow passing namespace to `switch ns`

Right now it doesn't seem like you can pass a namespace to using switch ns. For example, if I have a namespace test, i should be able to use switch ns test and I will be switched over to that namespace. Right now, it pops up the search, which isn't bad. But it could be faster in the cases I know the namespace name I want to switch over to.

GKE Store: Generate correct kubeconfig for k8s > 1.25.0

Today, when using the kubeconfig generated by kubeswitch with kubectl > 1.22, we get the following warning

WARNING: the gcp auth plugin is deprecated in v1.22+, unavailable in v1.25+; use gcloud instead.
To learn more, consult https://cloud.google.com/blog/products/containers-kubernetes/kubectl-auth-changes-in-gke

Please see here for more information.

Currently, the user section of the kubeconfig is generated like so:

users:
- name: gke_dev-garden-gcp
  user:
    auth-provider:
      config:
        access-token: <token>
        cmd-args: config config-helper --format=json
        cmd-path: /usr/local/bin/gcloud
        expiry: "2022-05-17T09:39:22Z"
        expiry-key: '{.credential.token_expiry}'
        token-key: '{.credential.access_token}'
      name: gcp

in the future it should look like so

  • note the use of the new gke-gcloud-auth-plugin (must be installed on the client side!)
  • note the absent of the ID token
users:
- name: NEW-CONFIG
  user:
    exec:
      apiVersion: client.authentication.k8s.io/v1beta1
      command: gke-gcloud-auth-plugin
      installHint: Install gke-gcloud-auth-plugin for use with kubectl by following
        https://cloud.google.com/blog/products/containers-kubernetes/kubectl-auth-changes-in-gke
      provideClusterInfo: true

[RFE] Optionally include the file name when searching for contexts

Currently:

❯ find .kube/configs -type f
.kube/configs/ha-edge-385.yaml
.kube/configs/vm-k3s-only.yaml

❯ cat .kube/switch-config.yaml
kind: SwitchConfig
version: v1alpha1
kubeconfigStores:
- kind: filesystem
  kubeconfigName: "*.yaml"
  paths:
  - /Users/eminguez/.kube/configs/
  - /Users/eminguez/.kube/config

❯ switch list-contexts
configs/default
configs/default

Ideally:

❯ switch list-contexts
configs/default (ha-edge-385.yaml)
configs/default (vm-k3s-only.yaml)

Support for MS Windows

Is there a reason why you don't provide the Windows binaries too ?

First I thought there might be some dependency that doesn't exist on Windows. But I was able to build the binary on my own and it seems to work (have to check this more thoroughly).
Or are there some known things that don't work ?

Additional remarks:

  • no, Windows isn't my preferred operating system but sometimes you can't choose ;-)
  • I assume that kubeswitch can be used without the switch.sh (or an equivalent) at least to a certain degree

Error: the configured kubeconfig directory {"/Users/USERNAME/.kube/config" "filesystem"} does not exist

When executing Switcher in whatever dir on my MacOS I get the following err:

Error: the configured kubeconfig directory {"/Users/USERNAME/.kube/config" "filesystem"} does not exist
the configured kubeconfig directory {"/Users/USERNAME/.kube/config" "filesystem"} does not exist

! When there is no default Kubeconfig file in the ~/.kube/ directory (meaning the config file).


So. Is it a requirement to have a default Kubeconfig config file in ~/.kube for things to work?

From reading Configure Kubeconfig stores I do not get the impression that this is the case.

I can get things to work by having whatever Kubeconfig config file in the ~/.kube/ folder. But, I'd rather not.

Looking forward to some pointers. Thank you 😄

Rancher store

Rancher's CLI tool allows you to run rancher cluster kubeconfig <name> and returns a kubeconfig YAML.

CLI entrypoint is here https://github.com/rancher/cli/blob/7c7f747d32b2fe848d09dd90f95ef82bc9be25db/cmd/cluster.go#L474

That seems to call https://github.com/rancher/rancher/blob/ba4347297ef8984f629650979a1b3a470592f4da/pkg/client/generated/management/v3/zz_generated_cluster.go#L184

Not quite sure which actual URL is called behind that, but I'll look into it (and plan to PR a rancher store provider)

Option to disable prefix of kubeconfig (filesystem)

Follow up to comment #18 (comment)

Please provide an option to disable the prefix of kubeconfig:

image

$ cat ~/.kube/config.CLEAN
apiVersion: v1
clusters:
  - cluster:
        insecure-skip-tls-verify: true
        server: https://api.vmw.example.com:6443
    name: api-vmw-example-com:6443
contexts:
  - context:
        cluster: api-vmw-example-com:6443
        namespace: windows-container
        user: kube:admin/api-vmw-example-com:6443
    name: windows-container/api-vmw-example-com:6443/kube:admin
  - context:
        cluster: api-vmw-example-com:6443
        namespace: windows-workload
        user: kube:admin/api-vmw-example-com:6443
    name: windows-workload/api-vmw-example-com:6443/kube:admin
current-context: demo-app/api-demo-openshift-pub:6443/admin
kind: Config
preferences: {}
users:
  - name: kube:admin/api-vmw-example-com:6443
    user:
        token: sha256~A518ZtBiOcuyuYuYWk96-NTgZaJh_vfqomZ-SyXTNpc
$ switch --show-preview=false --kubeconfig-path ~/.kube/config.CLEAN

Thanks
Robert

Can it work without permissions to scan for namespaces ?

At the company I work for we are not allowed to scan for namespaces. When I try to do so I am denied and when using kubectl I have to pay attention not to forget the -n foo parameter.

I gave kubeswitch a try and it seems to fail for the same reason:

2023/02/23 08:14:16 error from api: namespaces is forbidden: User "menotyou" cannot list resource "namespaces" in API group "" at the cluster scope

Using the switch config I told kubeswitch to use a single kubeconfig file. All of my kubeconfig files (I have one per cluster/context) have the namespace configured so that I only need to do something like KUBECONFIG=~/config/config1.yml kubectl get po and can dump the -n.

- context:
    cluster: ...
    user: ...
  name: ...
  namespace: foo

I assume that kubeswitch always scans for namespaces even if (in my scenario) this is undesired / not necessary. I really would like to use kubeswitch but I guess in the current state I can't use it. Am I right ? Or is there a workaround ?

Multiple kubeconfig names

Currently the utility can only be configured to search for kubeconfig files with a certain name.
Make it possible to be able to specify multiple names.

Support EKS

Supporting Amazon EKS seems to be possible

  • Golang SDK for EKS can be found here.
  • For authentication with the SDK, see here

It seems like that each region needs to be specified when authenticating or rely on the default credentials at .aws/credentials and .aws/config. This makes configuration in kubeswitch slightly more cumbersome than for GKE.

On top of that, EKS does not have a free tier for development :(
If someone uses EKS already and wants to see EKS being supported by kubeswitch, this is your chance :)

GKE store: no projects found in Google Cloud

Prerequisites:

# ~/.kube/switch-config.yaml
kind: SwitchConfig
version: "v1alpha1"
kubeconfigStores:
  - kind: gke
    id: gke
    config:
      authentication:
        authenticationType: gcloud
      # optionally limit to certain projects in account
      # projectIDs: []

Steps to reproduce:

  1. Run switch (Google Cloud Authorization opens in a web browser)
  2. Allow access
  3. Wait a little bit, then exit from switch

Result:

$ switch
WARN[0021] Supressed warnings during the search: 1 error occurred:
        * store "gke.gke" returned an error during the search: failed to initialize store: no projects found in Google Cloud. Unable to discover GKE clusters

Error: abort

Expected

A list of GKE clusters. There are definitely some projects:

$ gcloud projects list | wc -l
5

And some GKE clusters:

$ gcloud container clusters list | wc -l
2

Additional information

Kubeswitch version info:

Switch:
		version     : v0.7.2
		build date  : 2022-09-20
		go version  : go1.19
		go compiler : gc
		platform    : linux/amd64

Gcloud version info:

Google Cloud SDK 404.0.0
alpha 2022.09.23
beta 2022.09.23
bq 2.0.78
bundled-python3-unix 3.9.12
core 2022.09.23
gcloud-crc32c 1.0.0
gke-gcloud-auth-plugin 0.4.0
gsutil 5.14

odd bugs

$ switch --config-directory ~/.kube
Error: unknown flag: --config-path

and README says to use --kubeconfig-directory.. but thats not listed in the --help output ?

Add --version flag

We need a --version flag to identify the currently used kubeswitch version.

`showPrefix: false` doesn't work together with `id:` ?

Hi,

the following configuration shows the .kube prefix but it should not:

$ switch version
Switch:
		version     : v0.4.5
		build date  : 2021-05-22
		go version  : go1.15.12
		go compiler : gc
		platform    : linux/amd64
$ cat ~/.kube/switch-config.yaml
kind: SwitchConfig
version: v1alpha1
showPreview: false
kubeconfigStores:
- kind: filesystem
  id: local
  refreshIndexAfter: 3h
  showPrefix: false
  paths:
  - ~/.kube/config
$switch

image

If I remove the id: local it works as expected.

Cheers
Robert

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.