k8sctx

package module
v1.0.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Jan 3, 2025 License: MIT Imports: 11 Imported by: 0

README

K8sCtx - Kubernetes Context (Switcher)

Change your kube context via ktx command.

Go Report Card Coverage Status Go Reference

Features

  • support for multiple kubeconfigs (globally - not per terminal session; see Extras)
  • add aliases for kubeconfig files
  • add aliases for the kube contexts
  • fuzzy search a context via Terminal User Interface (short TUI)
  • jump back and forth between two contexts via ktx -
  • manage your contexts in an extra config file with the help of Jsonnet
  • or manage your contexts in different extra contexts_<kubeconfig alias>.yaml files; one per kubeconfig

Usage

  • Opens the TUI in Filter mode with all contexts of all kubeconfig files:
ktx


  • Opens the TUI in Filter mode with all contexts of a kubeconfig file with the alias "d":
ktx d


  • Opens the TUI in Select mode with contexts filtered by "lab" of the kubeconfig with the alias "d":
ktx d lab


  • Switches to the previous context (no TUI involved):
ktx -

  • Switches directly to the context with the name/alias "cluster-lab-oci-eu-frankfurt-1-dev" (no TUI involved):
ktx -c cluster-lab-oci-eu-frankfurt-1-dev

  • Returns the current context (no TUI involved):
ktx -c

Installation

[!NOTE] Before you run the next command, make sure you have go installed.

Run the following command to install the binary on your local machine:

go install -v github.com/peterbueschel/k8sctx@latest

Configuration

On a first run, the tool will create a folder called ktx and the required files inside the user config folder (under Linux it is usually ~/.config/; under Windows it is APPDATA).

[!NOTE] You can define a different location with the help of the KTX_CONFIG_DIR environment variable.

The required files are:

filename content description
config.jsonnet Settings for ktx itself and every context in all kubeconfigs. The main config file written in jsonnet for ktx, which is also used to update the different contexts_<alias>.yaml files.

🔗 see config_jsonnet for more details.
contexts_<alias>.yaml Settings for the contexts of a single kubeconfig. For every kubeconfig (given by its <alias>), such a .yaml will be generated. Inside, you can set in turn an alias for each context next to other fields, like environment or region. These fields will be shown in the TUI.
Here you could theoretically also specify the default namespace, but it is more recommended to use the config.jsonnet.

⚠️ If you delete such .yaml file, the tool will automatically recreate it with the help of the config.jsonnet.
.libsonnet Jsonnet code used by the config.jsonnet in order to import all contexts_<alias>.yaml files. This is a helper file for the config.jsonnet. It makes the content of all contexts_<alias>.yaml files available under the alias of the related kubeconfig.

This file doesn't need to be touched.
.state Stores the last & current context, together with the related kubeconfig This file is required for the ktx - command in order to jump back and forth between two contexts.

TUI

The TUI was made with the help of the charmbracelet/bubbletea framework.

It has two modes:

  • the Filter mode (using a fuzzy search)
  • and the Select mode

which are used based on the way you run the ktx tool (see Usage)

You can switch between the modes by pressing the esc key and the / key, where:

  • pressing esc in the Filter mode will enter the Select mode
  • and pressing the / key in the Select mode will return to the Filter mode

Depending on your settings, you can filter by either the name of the context or its alias.

Leave the TUI without changing the context via q in Select mode or directly via ctrl + c.

Extras

Setup Multiple Kubeconfigs

According to the official Kubernetes documentation:

The KUBECONFIG environment variable is a list of paths to configuration files. The list is colon-delimited for Linux and Mac, and semicolon-delimited for Windows.

# Example: Multiple Kube config files - one per environment
export KUBECONFIG="$HOME/.kube/config.lab:$HOME/.kube/config.ed:$HOME/.kube/config.stage:$HOME/.kube/config.live"
Using the config.jsonnet file

Please have a look into extra documentation file: docs/config_jsonnet.md

Documentation

Index

Constants

This section is empty.

Variables

View Source
var (
	ErrReadConfig     = errors.New("failed to read from context config file")
	ErrParseConfig    = errors.New("failed to parse context config file")
	ErrReadStateFile  = errors.New("failed to parse state file")
	ErrParseStateFile = errors.New("failed to parse state file")
)
View Source
var (
	ErrReadKubeConfig  = errors.New("failed to read from kube config file")
	ErrParseKubeConfig = errors.New("failed to parse kube config file")
	ErrDuplContext     = errors.New("duplicated context name")
	ErrNoContext       = errors.New("no context found")
)

Functions

This section is empty.

Types

type Config

type Config struct {
	// Dir of the config files
	Dir string
	// GlobalConfig holds the jsonnet file path of the context config
	GlobalConfig string
	// KubeConfs is list of kube config items. With allows you to
	// handle multiple kube configs with a single "GlobalConfig".
	KubeConfs []*KubeConf `json:"kube_configs"`
	// State contains the name of the state file
	// LastConf, CurrentContext and LastContext
	*State `json:"state"`
}

Config is the main struct, which is generated from the config file and holds one or more kube configs.

func Get

func Get(config string) (*Config, error)

Get reads the config.jsonnet file and the bound kube config files. In addition, if not exist, it creates the contexts and state files.

func (*Config) CreateListItems

func (c *Config) CreateListItems(filterConfig, filterContext string) []ContextItem

CreateListItems is a helper function for the TUI and creates the list of context names and a description.

func (*Config) GetContextBy

func (c *Config) GetContextBy(name string) (*KubeConf, map[string]string, int)

GetContextBy takes a name or alias of the desired context as argument and returns the KubeConf, the context and its index.

func (*Config) GetKubeConfigBy

func (c *Config) GetKubeConfigBy(path string) *KubeConf

GetKubeConfigBy returns the KubeConf by a given path.

func (*Config) GetState

func (c *Config) GetState() error

GetState stores the current state file content into the config. It returns ErrReadStateFile or ErrReadStateFile if the .state file cannot be read or parsed.

func (*Config) RemoveCurrentContexts

func (c *Config) RemoveCurrentContexts() error

RemoveCurrentContexts removes from every kube config the setting for the currentContext.

func (*Config) SyncNamespaces

func (c *Config) SyncNamespaces() error

SyncNamespaces loops over the KubeConf and runs in turn the SyncNamespaces for every kube config.

func (*Config) UpdateState

func (c *Config) UpdateState(k *KubeConf, currentContext string) error

UpdateState stores the actual kube config and context under the lastConfig and lastContext inside the .state file. At the same time it updates the values for the current config and current context.

type Context

type Context struct {
	Cluster   string `yaml:"cluster"`
	User      string `yaml:"user"`
	Namespace string `yaml:"namespace,omitempty"`
}

Context item.

type ContextItem

type ContextItem struct {
	Name        string
	Description string
}

ContextItem is used in the "list" Model in the cmd/ktx.

type KubeConf

type KubeConf struct {
	// Path of the kube config file
	Path string `json:"path"`
	// Alias the kube config file
	Alias string `json:"alias"`
	// ContextFile holds the path of the context file in yaml format
	ContextFile string `json:"context_file"`
	// Contexts will be synced with the kube config file
	// and extended by the GlobalConfig file
	Contexts []map[string]string `json:"contexts"`
	// KubeConfig holds the kube config file content
	KubeConfig *KubeConfig `json:"-"`
}

KubeConf stores the content of a single kube config file.

func (*KubeConf) Exists

func (k *KubeConf) Exists(name string) bool

Exists returns true if a context with the given name exists.

func (*KubeConf) GetContextBy

func (k *KubeConf) GetContextBy(name string) (map[string]string, int)

GetContextBy returns the context and its index within a single KubeConf given by name.

func (*KubeConf) Save

func (k *KubeConf) Save() error

Save writes the contexts stored in a KubeConfig into a contexts_<alias>.yaml file.

func (*KubeConf) SyncNamespaces

func (k *KubeConf) SyncNamespaces() error

SyncNamespaces loops over the contexts and updates the namespace in the underlying kube config file.

type KubeConfig

type KubeConfig struct {
	// Path holds the file path of the kube config.
	Path string `yaml:"-"`
	// APIVersion comes from the underlying K8s Kube Config specs.
	APIVersion string `yaml:"apiVersion"`
	// Kind comes from the underlying K8s Kube Config specs.
	Kind string `yaml:"kind"`
	// Preferences comes from the underlying K8s Kube Config specs.
	Preferences interface{} `yaml:"preferences"`
	// Contexts comes from the underlying K8s Kube Config specs and will be
	// next to the CurrentContext interesting part for us.
	Contexts []KubeContext `yaml:"contexts"`
	// CurrentContext contains the desired context name.
	CurrentContext string `yaml:"current-context"`
	// Clusters comes from the underlying K8s Kube Config specs.
	Clusters []struct {
		Name    string      `yaml:"name"`
		Cluster interface{} `yaml:"cluster"`
	} `yaml:"clusters"`
	// Users comes from the underlying K8s Kube Config specs.
	Users []struct {
		Name string      `yaml:"name"`
		User interface{} `yaml:"user"`
	} `yaml:"users"`
}

KubeConfig holds the content of the kube config file.

func GetKubeConfig

func GetKubeConfig(kubeconfig string) (*KubeConfig, error)

func (*KubeConfig) AddNamespaceTo

func (k *KubeConfig) AddNamespaceTo(contextName, namespace string) error

func (*KubeConfig) GetContextBy

func (k *KubeConfig) GetContextBy(name string) (*KubeContext, int, error)

GetContextBy returns the kube context by a given name

func (*KubeConfig) GetContextNames

func (k *KubeConfig) GetContextNames() (names []string)

GetProfilesNames returns all context names

func (*KubeConfig) Read

func (k *KubeConfig) Read() error

func (*KubeConfig) RemoveCurrentContext

func (k *KubeConfig) RemoveCurrentContext() error

func (*KubeConfig) SaveContexts

func (k *KubeConfig) SaveContexts() error

func (*KubeConfig) SetContextTo

func (k *KubeConfig) SetContextTo(contextName string) error

func (*KubeConfig) SyncContexts

func (k *KubeConfig) SyncContexts(c *KubeConf) error

type KubeConfigs

type KubeConfigs []KubeConfig

type KubeContext

type KubeContext struct {
	Name     string `yaml:"name"`
	*Context `yaml:"context"`
}

KubeContext holds a single context.

type State

type State struct {
	// Filename of the state file
	Filename string `yaml:"filename"`
	// CurrentConf holds the name of the curently used kube config. This
	// is used to jump back via "-" argument of the ktx cli command.
	CurrentConf string `yaml:"currentKubeConfig"`
	// LastConf stores the name of the previous used kube config. This
	// is used to jump back via "-" argument of the ktx cli command.
	LastConf string `yaml:"lastKubeConfig"`
	// CurrentContext stores the name of the currently used Kubernetes context.
	CurrentContext string `yaml:"currentContext"`
	// LastContext together with LastConf will be used to switch between
	// two contexts.
	LastContext string `yaml:"lastContext"`
}

State is used to switch back to the previous contexts.

Directories

Path Synopsis
cmd
ktx command

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL