我有Kubernetes在两个不同的环境中工作得很好,即在我的本地环境(MacBook运行minikube)和谷歌的容器引擎(GCE, Kubernetes在谷歌云上)。我使用MacBook/local环境来开发和测试我的YAML文件,然后,完成后,在GCE上尝试它们。

目前我需要单独使用每个环境:我需要在我的本地环境中编辑YAML文件,当准备就绪时,(git)将它们克隆到GCE环境中,然后使用/部署它们。这是一个有点麻烦的过程。

理想情况下,我想从我的Macbook使用kubectl来轻松地在本地minikube或GCE Kubernetes环境之间切换,并轻松地确定在哪里使用YAML文件。有没有一种简单的方法来切换上下文来做到这一点?


当前回答

TL;DR:我创建了一个GUI来通过AppleScript切换Kubernetes上下文。我通过shift-cmd-x激活它。

我也有同样的问题。这是一个痛苦的切换上下文的命令行。我使用FastScripts设置了一个键组合(shift-cmd-x)来运行以下AppleScript(放在这个目录:$(HOME)/Library/Scripts/Applications/Terminal)。

use AppleScript version "2.4" -- Yosemite (10.10) or later
use scripting additions

do shell script "/usr/local/bin/kubectl config current-context"
set curcontext to result

do shell script "/usr/local/bin/kubectl config get-contexts -o name"
set contexts to paragraphs of result

choose from list contexts with prompt "Select Context:" with title "K8s Context Selector" default items {curcontext}
set scriptArguments to item 1 of result

do shell script "/usr/local/bin/kubectl config use-context " & scriptArguments

display dialog "Switched to " & scriptArguments buttons {"ok"} default button 1

其他回答

我厌倦了一遍又一遍地输入这个,所以我写了一个简单的bash实用程序来切换上下文

你可以在这里找到它https://github.com/josefkorbel/kube-switch

是的,我想这就是你要问的问题。要查看当前配置,请使用kubectl配置视图。Kubectl从以下位置加载并合并配置(按顺序)

--kubeconfig=/path/to/.kube/config command line flag
KUBECONFIG=/path/to/.kube/config env variable
$HOME/.kube/config  - The DEFAULT

我使用——kubecconfig,因为我经常在多个集群之间切换。它有点麻烦,但它工作得很好。

更多信息请看这些。 https://kubernetes.io/docs/tasks/administer-cluster/share-configuration/和https://kubernetes.io/docs/concepts/cluster-administration/authenticate-across-clusters-kubeconfig/

最新的2020年答案在这里,

一个简单的方法切换kubectl上下文,

kubectl top nodes **--context=**context01name

kubectl top nodes --context=context02name

您还可以将上下文名称存储为env like context01name = gke_ $ {GOOGLE_CLOUD_PROJECT} _us-central1-a_standard-cluster-1

上下文列表

kubectl config get-contexts

上下文切换

kubectl config set current-context MY-CONTEXT

TL;DR:我创建了一个GUI来通过AppleScript切换Kubernetes上下文。我通过shift-cmd-x激活它。

我也有同样的问题。这是一个痛苦的切换上下文的命令行。我使用FastScripts设置了一个键组合(shift-cmd-x)来运行以下AppleScript(放在这个目录:$(HOME)/Library/Scripts/Applications/Terminal)。

use AppleScript version "2.4" -- Yosemite (10.10) or later
use scripting additions

do shell script "/usr/local/bin/kubectl config current-context"
set curcontext to result

do shell script "/usr/local/bin/kubectl config get-contexts -o name"
set contexts to paragraphs of result

choose from list contexts with prompt "Select Context:" with title "K8s Context Selector" default items {curcontext}
set scriptArguments to item 1 of result

do shell script "/usr/local/bin/kubectl config use-context " & scriptArguments

display dialog "Switched to " & scriptArguments buttons {"ok"} default button 1