zl程序教程

您现在的位置是:首页 >  工具

当前栏目

kubectx-切换集群工具

工具集群 切换
2023-09-14 09:15:46 时间

kubectx 帮助您在集群之间来回切换

install

由于 kubectx/kubens 是用 Bash 编写的,因此您应该能够将它们安装到任何安装了 Bash 的 POSIX 环境中。

git clone https://github.com/ahmetb/kubectx /opt/kubectx

确保 kubectx 脚本是可执行的

[root@myk8s1 ~] ls /opt/kubectx/ -ltr
total 40
-rw-r--r-- 1 root root 11357 Feb 17 21:25 LICENSE
-rw-r--r-- 1 root root   968 Feb 17 21:25 CONTRIBUTING.md
-rw-r--r-- 1 root root  7784 Feb 17 21:25 README.md
drwxr-xr-x 2 root root   121 Feb 17 21:25 completion
drwxr-xr-x 2 root root    84 Feb 17 21:25 img
drwxr-xr-x 3 root root   100 Feb 17 21:25 test
-rwxr-xr-x 1 root root  5273 Feb 17 21:25 kubens
-rwxr-xr-x 1 root root  5218 Feb 17 21:25 kubectx

从 PATH 中的某个位置创建指向 kubectx/kubens 的符号链接,例如 /usr/local/bin

ln -s /opt/kubectx/kubectx /usr/local/bin/kubectx

usage

you should first understand how to switch among different clusters by using configuration files. please investigate this link, actually kubectx is built on top of it.

for example, I have one cluster on AWS and one cluster on Fyre, in each cluster there is a ~/.kube/config file, rename it as config.aws and config.fyre and put them to another client machine ~/.kube/ folder with kubectl installed.

[root@centctl1 .kube]# ls -ltr
total 16
drwxr-xr-x 3 root root   23 Nov 26 16:38 cache
-rw-r--r-- 1 root root 2214 Dec  6 10:16 config.aws
drwxr-xr-x 2 root root   73 Dec  6 10:16 kubens
drwxr-xr-x 3 root root 4096 Feb 17 22:05 http-cache
-rw------- 1 root root 5474 Feb 17 22:22 config.fyre

append config files to environment variable KUBECONFIG, you can add export to .bashrc file.

export KUBECONFIG=$KUBECONFIG:$HOME/.kube/config.aws:$HOME/.kube/config.fyre

now if you run kubectx you will see there are 2 contexts

[root@centctl1 .kube] kubectx
arn:aws:eks:us-west-2:296744932886:cluster/IIS-Test-Cluster
kubernetes-admin@kubernetes

switch to kubernetes-admin@kubernetes

[root@centctl1 .kube] kubectx kubernetes-admin@kubernetes
Switched to context "kubernetes-admin@kubernetes".

switch back

[root@centctl1 .kube] kubectx -
Switched to context "arn:aws:eks:us-west-2:296744932886:cluster/IIS-Test-Cluster".

actually the effect is the same as

kubectl config view
kubectl config --kubeconfig=config.fyre use-context kubernetes-admin@kubernetes