kubectl 配置/切换 不同的集群环境

查看kubectl config命令的help

[root@k8s001 cfg]# kubectl config --help
Modify kubeconfig files using subcommands like "kubectl config set current-context my-context"

 The loading order follows these rules:

  1.  If the --kubeconfig flag is set, then only that file is loaded. The flag may only be set once and no merging takes
  2.  If $KUBECONFIG environment variable is set, then it is used as a list of paths (normal path delimiting rules for
your system). These paths are merged. When a value is modified, it is modified in the file that defines the stanza. When
a value is created, it is created in the first file that exists. If no files in the chain exist, then it creates the
last file in the list.
  3.  Otherwise, ${HOME}/.kube/config is used and no merging takes place.

Available Commands:
  current-context Displays the current-context
  delete-cluster  Delete the specified cluster from the kubeconfig
  delete-context  Delete the specified context from the kubeconfig
  get-clusters    Display clusters defined in the kubeconfig
  get-contexts    Describe one or many contexts
  rename-context  Renames a context from the kubeconfig file.
  set             Sets an individual value in a kubeconfig file
  set-cluster     Sets a cluster entry in kubeconfig
  set-context     Sets a context entry in kubeconfig
  set-credentials Sets a user entry in kubeconfig
  unset           Unsets an individual value in a kubeconfig file
  use-context     Sets the current-context in a kubeconfig file
  view            Display merged kubeconfig settings or a specified kubeconfig file

  kubectl config SUBCOMMAND [options]

Use "kubectl <command> --help" for more information about a given command.
Use "kubectl options" for a list of global command-line options (applies to all commands).


# 把所有环境kubeconfig文件中的name和current-context字段修改成各环境对应的名称,比如:aliyun-k8s
- context:
    cluster: kubernetes
    namespace: deepflow-demo-3tier-svc
    user: kubernetes-admin
  name: yunshan-poc-k8s
current-context: yunshan-poc-k8s


# 指定k8s的kubeconfig文件路径,我这里是在/root/.kube/下面,多个kubeconfig文件用 : 号分割
echo "export KUBECONFIG=$HOME/.kube/yunshan-poc-k8s:$HOME/.kube/aliyun-k8s" >> ~/.base_profile
source ~/.bash_profile


kubectl config get-contexts


kubectl config use-context yunshan-poc-k8s


# 查看当前使用环境
kubectl config current-context
# 查看当前环境node节点
kubectl get node


1 + 1 =