多集群的切换是K8s运维中比不可少的问题,常见的基于多个集群进行切换的方法有三种:
- 切换config文件
- 通过context进行集群切换
- 用kubectl-plugins进行集群切换
切换config文件
我们先看看放在.kube
下默认的config集群:
$ kubectl config view
apiVersion: v1
clusters:
- cluster:
certificate-authority-data: DATA OMITTED
server:
name: kubernetes
contexts:
- context:
cluster: kubernetes
user: "212785087522004927"
name: 212785087522004927-c02e82b6adaf044bd94d251fea1279648
current-context: 212785087522004927-c02e82b6adaf044bd94d251fea1279648
kind: Config
preferences: {}
users:
- name: "212785087522004927"
user:
client-certificate-data:
client-key-data:
通过export
更改默认集群配置:
$ export KUBECONFIG=$HOME/.kube/rancher-config
查看:
代码语言:javascript复制$ kubectl config view
apiVersion: v1
clusters:
- cluster:
certificate-authority-data: DATA OMITTED
server:
name: stage
contexts:
- context:
cluster: stage
user: stage
name: stage
current-context: stage
kind: Config
preferences: {}
users:
- name: stage
user:
token:
这种方法就是特别麻烦,每次切换都要通过export设置,非常麻烦,同时也不方便。
通过context进行集群切换
把要切换的所有config文件添加到KUBECONFIG
环境变量中
$ export KUBECONFIG=$HOME/.kube/config:$HOME/.kube/rancher-config
或者可以将命令直接写到.bashrc
文件中,这样就不需要每次手动设置。
通过kubectl config view
可以看到这两个文件已经合并到一起了:
$ kubectl config view
apiVersion: v1
clusters:
- cluster:
certificate-authority-data: DATA OMITTED
server:
name: kubernetes
- cluster:
certificate-authority-data: DATA OMITTED
server:
name: stage
contexts:
- context:
cluster: kubernetes
user: "212785087522004927"
name: 212785087522004927-c02e82b6adaf044bd94d251fea1279648
- context:
cluster: stage
user: stage
name: stage
current-context: 212785087522004927-c02e82b6adaf044bd94d251fea1279648
kind: Config
preferences: {}
users:
- name: "212785087522004927"
user:
client-certificate-data:
client-key-data:
- name: stage
user:
token:
合并一起后就可以通过use-context
切换上下文来切换集群:
# 切换stage集群
$ kubectl config use-context stage
Switched to context "stage".
切换到第二个集群:
代码语言:javascript复制$ kubectl config use-context 212785087522004927-c02e82b6adaf044bd94d251fea1279648
Switched to context "212785087522004927-c02e82b6adaf044bd94d251fea1279648".
但这种方法不方便的地方就在如果context很多的时候,不方便查看。
通过kubectl-plugins切换集群
针对不方便查看我们可以永kubectl-plugins
来解决。kubectl-plugins 是一个对kubectl
的增强插件。
kubectl-glugins
安装:
git clone https://github.com/jordanwilson230/kubectl-plugins.git
cd kubectl-plugins
./install-plugins.sh
source ~/.bash_profile
通过switch cluster
切换集群:
$ kubectl switch cluster stage
CURRENT NAME CLUSTER AUTHINFO NAMESPACE
212785087522004927-c02e82b6adaf044bd94d251fea1279648 kubernetes 212785087522004927 stage
* stage stage stage