如果我在不同的终端会话中与不同的 kubernetes 集群交互,而不必一直切换上下文,会怎么样?

How if I interact with different kubernetes clusters in different terminals sessions with out having to switch contexts all the the time?

我现在正在测试角色差异,所以我有每个角色设置的上下文。

终端会话 Admin,我希望能够在一个会话中使用上下文 Admin,以便我可以根据需要更新规则。

在终端会话 User 中,我希望能够通过其上下文测试该角色。

(注意:我使用 EKS,因此角色映射到 IAM 角色)

好吧,我是个白痴。

kubectl 的 --help 输出中没有答案,但是,手册页中有此输出。

所有需要做的就是将 --context 标志放入他们的命令中。

您可以创建位于 ~/.kube/config 下的上下文文件的副本,并在 2 个不同的 shell 中,使用第一个 export KUBECONFIG=/path/to/kubeconfig1 和 [=12= 指向 2 个不同的配置文件] 二号。您可以编辑这些文件以具有 2 个不同的上下文 selected.

为了方便selectcontexts/switch他们之间,可以使用kubectx,.

我一直喜欢 kubectx 作为一种快速切换上下文的方式。如果您使用 aws-iam-authenticator 正确设置了上下文,就像这样:

users:
- name: kubernetes-admin
  user:
    exec:
      apiVersion: client.authentication.k8s.io/v1alpha1
      command: aws-iam-authenticator
      args:
        - "token"
        - "-i"
        - "<cluster_id>"
        - "-r"
        - "<admin_role_arn>"
- name: kubernetes-user
  user:
    exec:
      apiVersion: client.authentication.k8s.io/v1alpha1
      command: aws-iam-authenticator
      args:
        - "token"
        - "-i"
        - "<cluster_id>"
        - "-r"
        - "<user_role_arn>"

这应该可以让您轻松切换上下文。 (注意: 这假定了一种承担角色类型的情况。您也可以将 AWS_PROFILE 传递给 aws-iam-authenticator。)

以下是管理多个 kubectl 上下文的一些技巧:

  • 使用asdf管理多个kubectl版本
  • Set the KUBECONFIG 在多个 kubeconfig 文件之间切换的环境变量
  • 使用 kube-ps1 跟踪您当前的 context/namespace
  • 使用kubectx and kubens在clusters/namespaces
  • 之间快速变化
  • 使用别名将它们组合在一起

看看这篇文章,它解释了如何做到这一点:Using different kubectl versions with multiple Kubernetes clusters(免责声明:我写了提到的文章)

我还推荐这篇文章:Mastering the KUBECONFIG file and Configure Access to Multiple Clusters

现在,有了kubie。 https://github.com/sbstp/kubie

它做到了这一切。