背景:
我们通过会有多个k8s集群,例如集群(cn-k8s)和集群(jp-k8s),那个就需要有一台服务器可以同时访问两个集群,方式:将2个集群的config信息存放到一个文件中,通过使用 kubectl config use-context context_name 来访问集群。简而言之,通过设置context来让kubectl访问不同的k8s集群。

具体步骤如下:

假如已经准备好2个集群的配置文件,分别为 $HOME/.kube/config1 和 $HOME/.kube/config2 

config1 信息如下

[root@node-01 .kube]# cat $HOME/.kube/config1
apiVersion: v1
kind: Config
clusters:
- cluster:
    api-version: v1
    certificate-authority-data: xxxxxxx
    server: "https://172.20.8.113:6443"
  name: "cn-k8s"
contexts:
- context:
    cluster: "cn-k8s"
    user: "kube-admin-local"
  name: "cn-k8s"
current-context: "cn-k8s"
users:
- name: "kube-admin-local"
  user:
    client-certificate-data: xxxxxx
    client-key-data: xxxxxx

config2 信息如下

[root@node-01 .kube]# cat $HOME/.kube/config2
apiVersion: v1
kind: Config
clusters:
- cluster:
    api-version: v1
    certificate-authority-data: xxxxxx
    server: "https://172.19.8.113:6443"
  name: "jp-k8s"
contexts:
- context:
    cluster: "jp-k8s"
    user: "kube-admin-local"
  name: "jp-k8s"
current-context: "jp-k8s"
users:
- name: "kube-admin-local"
  user:
    client-certificate-data: xxxxxx
    client-key-data: xxxxxx

通过config信息,可以看到两个集群的cluster name,context name,以及用户信息。

配置文件已准备好,下面开始变身了。文件合成:

cd $HOME/.kube/config
KUBECONFIG=config1:config2 kubectl config view --flatten > $HOME/.kube/config

那么如何使用呢?

1、查看cluster name以及context name

[root@node-01 ~]# kubectl config view
apiVersion: v1
clusters:
- cluster:
    certificate-authority-data: DATA+OMITTED
    server: https://172.19.8.113:6443
  name: cnlocal
- cluster:
    certificate-authority-data: DATA+OMITTED
    server: https://172.19.8.113:6443
  name: jplocal
contexts:
- context:
    cluster: cnlocal
    user: kube-admin-local
  name: cnlocal
- context:
    cluster: jplocal
    user: kube-admin-local
  name: local
current-context: jplocal
kind: Config
preferences: {}
users:
- name: kube-admin-local
  user:
    client-certificate-data: REDACTED
    client-key-data: REDACTED

2、查看当前使用的集群

[root@node-01 ~]# kubectl config current-context
jplocal

3、修改当前使用的集群

[root@node-01 ~]# kubectl config use-context cnlocal
Switched to context "cnlocal".
02-13 02:12