CKA [Security] – Kubeconfig的创建

什么是 Kubeconfig?

Kubeconfig 是 Kubernetes 用来记录和管理集群连接信息的配置文件。

  • 可以包含多个集群、多用户、多上下文(context)。
  • 文件名通常是:~/.kube/config(默认位置)
  • 用于 kubectl 命令访问 Kubernetes 集群时提供身份验证、API 服务器地址、证书等信息。

Kubeconfig 文件结构

apiVersion: v1
kind: Config
clusters:
- name: my-cluster
  cluster:
    server: https://1.2.3.4:6443
    certificate-authority: /path/to/ca.crt

users:
- name: my-user
  user:
    client-certificate: /path/to/client.crt
    client-key: /path/to/client.key

contexts:
- name: my-context
  context:
    cluster: my-cluster
    user: my-user
    namespace: default

current-context: my-context

Kubeconfig 文件是一个 YAML 文件,主要包含以下 4 个字段:

clusters
– 定义了可用的 Kubernetes 集群地址及认证方式(例如 CA 证书)

users
– 定义访问集群的用户及凭证(证书/Token)

contexts
– 定义了某个“上下文”:指定了使用哪个集群 + 哪个用户 + 默认命名空间

current-context
– 当前活跃使用的上下文名称

命令行的使用

1. 添加cluster details
添加了clustername1连接到https://1.2.3.4 ,创建在当下目录的testfile当中,如果没有写kubeconfig的话,那么就是把这个cluster details添加入了默认目录当中。

kubectl config --kubeconfig=testfile set-cluster clustername1 --server=https://1.2.3.4

2. 添加user登入资料, user名是user1

kubectl config --kubeconfig=testfile set-credentials user1 --username=dev --password=some-password

3. 创建context,把用户和cluster做绑定, context名是ctx1

 kubectl config --kubeconfig=testfile set-context ctx1 --cluster=clustername1 --user=user1

4. 查看已创建的testfile

kubectl config view --kubeconfig=testfile

5. 获取当下context的信息

kubectl config --kubeconfig=testfile get-contexts

6. 可以切换到其他的context

kubectl config --kubeconfig=base-config use-context yourCtxName

Context Example

以下的例子是我当下有3个ctx,一开始默认选择了minikube ctx, 然后使用 use-context 进行切换

Loading

Facebook评论