[k8s] 创建sa类型的kubeconfig

1.创建ClusterRole对整个集群的configmap有管理权限,在my-namespace1和my-namespace2创建RoleBinding,将ClusterRole绑定到default空间的sa账户

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
kubectl apply -f my-configmap.yaml
...
---
apiVersion: v1
kind: ServiceAccount
metadata:
  name: my-configmap-updater
 
---
apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRole
metadata:
  name: configmap-updater
rules:
  - apiGroups: [""]
    resources: ["configmaps"]
    verbs: ["create", "update", "patch", "get", "list"]
 
---
apiVersion: rbac.authorization.k8s.io/v1
kind: RoleBinding
metadata:
  name: configmap-updater
  namespace: my-namesapce1
subjects:
- kind: ServiceAccount
  name: my-configmap-updater
  namespace: default
  apiGroup: ""
roleRef:
  kind: ClusterRole
  name: configmap-updater
  apiGroup: rbac.authorization.k8s.io
 
---
apiVersion: rbac.authorization.k8s.io/v1
kind: RoleBinding
metadata:
  name: configmap-updater
  namespace: my-namesapce2
subjects:
- kind: ServiceAccount
  name: my-configmap-updater
  namespace: default
  apiGroup: ""
roleRef:
  kind: ClusterRole
  name: configmap-updater
  apiGroup: rbac.authorization.k8s.io

  

2.生成ca.crt

1
2
3
user=my-configmap-updater
secret=$(kubectl get sa $user -o json | jq -r .secrets[].name)
kubectl get secret $secret -o json | jq -r '.data["ca.crt"]' | base64 -d > ca.crt

  

3.准备user_token、api地址

1
2
3
4
user_token=$(kubectl get secret $secret -o json | jq -r '.data["token"]' | base64 -d)
context=$(kubectl config current-context)
cluster=$(kubectl config get-contexts $context | awk 'NR>1{print $3}')
endpoint=$(kubectl config view -o jsonpath="{.clusters[?(@.name == \"$cluster\")].cluster.server}")

  

4.备份.kube/config,生成干净的config

1
2
3
4
5
6
7
8
9
10
11
12
13
14
mv ~/.kube/config ~/.kube/config.bak
 
kubectl config set-cluster $cluster \
   --embed-certs=true \
   --server=$endpoint \
   --certificate-authority=./ca.crt
    
kubectl config set-credentials $user --token=$user_token
 
kubectl config set-context $context \
   --cluster=$cluster \
   --user=$user
 
kubectl config use-context $context

  

5.拷贝走新的.kube/config,还原.kube/config.bak

 

参考:https://stackoverflow.com/questions/42170380/how-to-add-users-to-kubernetes-kubectl

posted @   金枪语  阅读(895)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· winform 绘制太阳,地球,月球 运作规律
· AI与.NET技术实操系列(五):向量存储与相似性搜索在 .NET 中的实现
· 超详细:普通电脑也行Windows部署deepseek R1训练数据并当服务器共享给他人
· 上周热点回顾(3.3-3.9)
· AI 智能体引爆开源社区「GitHub 热点速览」
点击右上角即可分享
微信分享提示