简体   繁体   English

如何在 gcloud 和 minikube 之间切换 kubectl 集群

[英]How to switch kubectl clusters between gcloud and minikube

I have Kubernetes working well in two different environments, namely in my local environment (MacBook running minikube) and as well as on Google's Container Engine (GCE, Kubernetes on Google Cloud).我让 Kubernetes 在两种不同的环境中运行良好,即在我的本地环境(运行 minikube 的 MacBook)和 Google 的容器引擎(GCE,Google Cloud 上的 Kubernetes)上。 I use the MacBook/local environment to develop and test my YAML files and then, upon completion, try them on GCE.我使用 MacBook/本地环境来开发和测试我的 YAML 文件,然后在完成后在 GCE 上试用它们。

Currently I need to work with each environment individually: I need to edit the YAML files in my local environment and, when ready, (git) clone them to a GCE environment and then use/deploy them.目前我需要单独处理每个环境:我需要在本地环境中编辑 YAML 文件,准备好后,(git) 将它们克隆到 GCE 环境,然后使用/部署它们。 This is a somewhat cumbersome process.这是一个有些麻烦的过程。

Ideally, I would like to use kubectl from my Macbook to easily switch between the local minikube or GCE Kubernetes environments and to easily determine where the YAML files are used.理想情况下,我想在我的 Macbook 上使用 kubectl 在本地 minikube 或 GCE Kubernetes 环境之间轻松切换,并轻松确定 YAML 文件的使用位置。 Is there a simple way to switch contexts to do this?有没有一种简单的方法来切换上下文来做到这一点?

You can switch from local (minikube) to gcloud and back with:您可以从本地(minikube)切换到 gcloud 并返回:

kubectl config use-context CONTEXT_NAME

to list all contexts:列出所有上下文:

kubectl config get-contexts

You can create different enviroments for local and gcloud and put it in separate yaml files.您可以为本地和 gcloud 创建不同的环境,并将其放在单独的 yaml 文件中。

List contexts列出上下文

kubectl config get-contexts

Switch contexts切换上下文

kubectl config set current-context MY-CONTEXT

A faster shortcut to the standard kubectl commands is to use kubectx :标准 kubectl 命令的更快快捷方式是使用kubectx

  • List contexts: kubectx列出上下文: kubectx
    • Equivalent to kubectl config get-contexts相当于kubectl config get-contexts
  • Switch context (to foo): kubectx foo切换上下文(到 foo): kubectx foo
    • Equivalent to kubectl config use-context foo相当于kubectl config use-context foo

To install on macOS: brew install kubectx在 macOS 上安装: brew install kubectx

The kubectx package also includes a similar tool for switching namespaces called kubens . kubectx 包还包括一个名为kubens的类似工具,用于切换命名空间。

These two are super convenient if you work in multiple contexts and namespaces regularly.如果您经常在多个上下文和命名空间中工作,这两个非常方便。

More info: https://ahmet.im/blog/kubectx/更多信息: https ://ahmet.im/blog/kubectx/

If you're looking for a GUI-based solution for Mac and have the Docker Desktop installed, you can use the Docker Menu Bar icon.如果您正在寻找适用于 Mac 的基于 GUI 的解决方案并安装了 Docker Desktop,则可以使用 Docker 菜单栏图标。 Here you can find "Kubernetes" menu with all the contexts you have in your kubeconfig and easily switch between them.在这里,您可以找到“Kubernetes”菜单,其中包含您在 kubeconfig 中拥有的所有上下文,并可以在它们之间轻松切换。

To get all context获取所有上下文

C:\Users\arun>kubectl config get-contexts

To get current context获取当前上下文

C:\Users\arun>kubectl config current-context

To switch context切换上下文

C:\Users\arun>kubectl config use-context <any context name from above list>

Latest 2020 answer is here, 2020年最新答案在这里,

A simple way to switch between kubectl context,一种在 kubectl 上下文之间切换的简单方法,

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

kubectl top nodes --context=context02name

You can also store the context name as env like context01name=gke_${GOOGLE_CLOUD_PROJECT}_us-central1-a_standard-cluster-1您还可以将上下文名称存储为 env,如 context01name=gke_${GOOGLE_CLOUD_PROJECT}_us-central1-a_standard-cluster-1

I got bored of typing this over and over so I wrote a simple bash utility to switch contexts我厌倦了一遍又一遍地输入这个,所以我写了一个简单的 bash 实用程序来切换上下文

在此处输入图像描述

You can find it here https://github.com/josefkorbel/kube-switch你可以在这里找到它https://github.com/josefkorbel/kube-switch

The canonical answer of switching/reading/manipulating different kubernetes environments (aka kubernetes contexts) is, as Mark mentioned, to use kubectl config , see below:切换/读取/操作不同的 kubernetes 环境(又名 kubernetes 上下文)的规范答案是,正如 Mark 提到的那样,使用kubectl config ,见下文:

$ kubectl config                                                                                                                                                                                                                 
Modify kubeconfig files using subcommands like "kubectl config set current-context my-context"

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

Usage:
  kubectl config SUBCOMMAND [options]

Behind the scene, there is a ~/.kube/config YAML file that stores all the available contexts with their corresponding credentials and endpoints for each contexts.在后台,有一个~/.kube/config YAML 文件,它存储所有可用的上下文及其相应的凭据和每个上下文的端点。

Kubectl off the shelf doesn't make it easy to manage different kubernetes contexts as you probably already know.正如您可能已经知道的那样,现成的 Kubectl 并不能使管理不同的 kubernetes 上下文变得容易。 Rather than rolling your own script to manage all that, a better approach is to use a mature tool called kubectx , created by a Googler named "Ahmet Alp Balkan" who's on Kubernetes / Google Cloud Platform developer experiences Team that builds tooling like this.与其使用自己的脚本来管理所有这些,更好的方法是使用名为kubectx的成熟工具,该工具由名为“Ahmet Alp Balkan”的 Google 员工创建,他在 Kubernetes / Google Cloud Platform 开发人员体验团队构建了这样的工具。 I highly recommend it.我强烈推荐它。

https://github.com/ahmetb/kubectx https://github.com/ahmetb/kubectx

$ kctx --help                                                                                                                                                                                                                  
USAGE:
  kubectx                       : list the contexts
  kubectx <NAME>                : switch to context <NAME>
  kubectx -                     : switch to the previous context
  kubectx <NEW_NAME>=<NAME>     : rename context <NAME> to <NEW_NAME>
  kubectx <NEW_NAME>=.          : rename current-context to <NEW_NAME>
  kubectx -d <NAME> [<NAME...>] : delete context <NAME> ('.' for current-context)
                                  (this command won't delete the user/cluster entry
                                  that is used by the context)

  kubectx -h,--help         : show this message

TL;DR: I created a GUI to switch Kubernetes contexts via AppleScript. TL;DR:我创建了一个 GUI 来通过 AppleScript 切换 Kubernetes 上下文。 I activate it via shift-cmd-x.我通过 shift-cmd-x 激活它。

I too had the same issue.我也有同样的问题。 It was a pain switching contexts by the command line.通过命令行切换上下文很痛苦。 I used FastScripts to set a key combo (shift-cmd-x) to run the following AppleScript (placed in this directory: $(HOME)/Library/Scripts/Applications/Terminal).我使用 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

Cloning the YAML files across repos for different environments is definitely ideal.跨存储库为不同环境克隆 YAML 文件绝对是理想的选择。 What you to do is templatize your YAML files - by extracting the parameters which differ from environment to environment.你要做的是模板化你的 YAML 文件——通过提取因环境而异的参数。

You can, of course, use some templating engine and separate the values in a YAML and produce the YAML for a specific environment.当然,您可以使用一些模板引擎并分离 YAML 中的值,并为特定环境生成 YAML。 But this is easily doable if you adopt the Helm Charts .但如果您采用Helm Charts ,这很容易实现。 To take a look at some sample charts go to stable directory at this Github repo要查看一些示例图表,请转到此Github 存储库中的稳定目录

To take an example of the Wordpress chart , you could have two different commands for two environments:Wordpress 图表为例,您可以针对两种环境使用两种不同的命令:

For Dev:对于开发:

helm install --name dev-release --set \ wordpressUsername=dev_admin, \ wordpressPassword=dev_password, \ mariadb.mariadbRootPassword=dev_secretpassword \ stable/wordpress

It is not necessary to pass these values on CLI though, you can store the values in a file called aptly values.yml and you could have different files for different environments虽然没有必要在 CLI 上传递这些值,但您可以将这些值存储在一个名为values.yml的文件中,并且您可以为不同的环境使用不同的文件

You will need some work in converting to Helm chart standards, but the effort will be worth it.您需要做一些工作才能转换为 Helm 图表标准,但这些努力是值得的。

Check also the latest (docker 19.03) docker context command .还要检查最新的 (docker 19.03) docker context command

Ajeet Singh Raina ) illustrates it in " Docker 19.03.0 Pre-Release: Fast Context Switching, Rootless Docker, Sysctl support for Swarm Services " Ajeet Singh Raina )在“ Docker 19.03.0 预发布版:快速上下文切换、无根 Docker、对 Swarm 服务的 Sysctl 支持”中对此进行了说明

上下文切换

A context is essentially the configuration that you use to access a particular cluster.上下文本质上是您用来访问特定集群的配置。

Say, for example, in my particular case, I have 4 different clusters – mix of Swarm and Kubernetes running locally and remotely.举例来说,在我的特定情况下,我有 4 个不同的集群——本地和远程运行的 Swarm 和 Kubernetes 的混合。
Assume that I have a default cluster running on my Desktop machine, 2 node Swarm Cluster running on Google Cloud Platform, 5-Node Cluster running on Play with Docker playground and a single-node Kubernetes cluster running on Minikube and that I need to access pretty regularly.假设我有一个默认集群在我的桌面机器上运行,2 节点 Swarm 集群在 Google Cloud Platform 上运行,5 节点集群在 Play with Docker playground 上运行,单节点 Kubernetes 集群在 Minikube 上运行,我需要访问 pretty经常。

Using docker context CLI I can easily switch from one cluster(which could be my development cluster) to test to production cluster in seconds.使用 docker context CLI,我可以在几秒钟内轻松地从一个集群(可能是我的开发集群)切换到测试生产集群。

$ sudo docker context --help
Usage:  docker context COMMAND
Manage contexts
Commands:
  create      Create a context
  export      Export a context to a tar or kubeconfig file
  import      Import a context from a tar file
  inspect     Display detailed information on one or more contexts
  ls          List contexts
  rm          Remove one or more contexts
  update      Update a context
  use         Set the current docker context
Run 'docker context COMMAND --help' for more information on a command.

For example:例如:

 [:)Captain'sBay=>sudo docker context ls NAME DESCRIPTION DOCKER ENDPOINT KUBERNETES ENDPOINT ORCHESTRATOR default * Current DOCKER_HOST based configuration unix:///var/run/docker.sock https://127.0.0.1:16443 (default) swarm swarm-context1

I use kubeswitch (disclaimer: I wrote the tool) that can be used just like kubectx , but is designed for a large number of kubeconfig files.我使用kubeswitch (免责声明:我编写了该工具),它可以像kubectx一样使用,但专为大量 kubeconfig 文件而设计。 If you have to deal with hundreds or thousands of kubeconfig files, this tool might be useful to you, otherwise kubectx or kubectl config use-context might be sufficient.如果你必须处理成百上千个 kubeconfig 文件,这个工具可能对你有用,否则kubectxkubectl config use-context可能就足够了。

For instance, it adds capabilities like reading from vault , hot reload while searching, and an index to speed up subsequent searches.例如,它添加了从vault读取、搜索时热重载以及加快后续搜索的索引等功能。

You can install it from here .您可以从这里安装它。

EDIT: now also includes support for GKE directly.编辑:现在还包括直接支持 GKE。 So you can use and discover kubeconfig files without having to manually download and update them.因此,您可以使用和发现 kubeconfig 文件,而无需手动下载和更新它们。

In case you might be looking for a simple way to switch between different contexts maybe this will be of help.如果您可能正在寻找一种在不同上下文之间切换的简单方法,那么这可能会有所帮助。

I got inspired by kubectx and kswitch scripts already mentioned, which I can recommend for most use-cases.我受到已经提到的kubectxkswitch脚本的启发,我可以推荐它们用于大多数用例。 They are helping with solving the switching task, but are breaking for me on some bigger or less standard configurations of ~/.kube/config .他们正在帮助解决切换任务,但在~/.kube/config的一些更大或更小的标准配置上对我来说是中断的。 So I created a sys-exec invocation wrapper and a short-hand around kubectl .所以我创建了一个 sys-exec 调用包装器和一个围绕kubectl的简写。

If you call k without params you would see an intercepted prompt to switch context.如果您在不带参数的情况下调用k ,您会看到一个截获的提示以切换上下文。

Switch kubectl to a different context/cluster/namespace.
Found following options to select from:
 >>> context: [1] franz
 >>> context: [2] gke_foo_us-central1-a_live-v1
 >>> context: [3] minikube
 --> new num [?/q]:

Further, k continues to act as a short-hand.此外, k继续充当简写形式。 The following is equivalent:以下是等效的:

kubectl get pods --all-namespaces
k get pods -A
k p -A

yes, i think this is what your asking about.是的,我想这就是你要问的。 To view your current config, use kubectl config view.要查看当前配置,请使用 kubectl config view。 kubectl loads and merges config from the following locations (in order) kubectl 从以下位置加载并合并配置(按顺序)

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

i use --kubeconfig since i switch alot between multiple clusters.我使用 --kubeconfig 因为我在多个集群之间切换了很多。 its slightly cumbersome but it works well.它有点麻烦,但效果很好。

see these for more info.查看这些以获取更多信息。 https://kubernetes.io/docs/tasks/administer-cluster/share-configuration/ and https://kubernetes.io/docs/concepts/cluster-administration/authenticate-across-clusters-kubeconfig/ https://kubernetes.io/docs/tasks/administer-cluster/share-configuration/https://kubernetes.io/docs/concepts/cluster-administration/authenticate-across-clusters-kubeconfig/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何轻松切换 gcloud / kubectl 凭据 - How to easily switch gcloud / kubectl credentials 如何使用 kubectl 在 Google Kube.netes Engine (GKE) 集群之间切换? - How can I switch between Google Kubernetes Engine (GKE) clusters with kubectl? kubectl 正在尝试连接到 gcloud 而不是 docker 桌面 - kubectl is trying to connect to gcloud instead of docker desktop 使用 gcloud container clusters create 创建的 GKE 集群后如何清理? - How to clean up after a GKE cluster created with gcloud container clusters create? 将 gcloud container clusters create --scope 转换为 Terraform 配置 - translating gcloud container clusters create --scope into a Terraform config gcloud 和 gsutil 有什么区别? - What is the difference between gcloud and gsutil? 不断获取权限错误 gcloud.container.clusters.get-credentials - Keep getting permissions error gcloud.container.clusters.get-credentials 如何安装或卸载 gcloud? - How to install or uninstall gcloud? ERROR: (gcloud.beta.container.clusters.create) ResponseError: code=400, message=v1 API 无法用于访问 GKE 区域集群 - ERROR: (gcloud.beta.container.clusters.create) ResponseError: code=400, message=v1 API cannot be used to access GKE regional clusters 如何启用在不同 AWS ECS 集群上运行的两个任务之间的通信 - How can i enable communication between two tasks running on different AWS ECS Clusters
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM