[k8s] 创建sa类型的kubeconfig

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

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

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地址

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

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 @ 2022-04-03 03:19  金枪语  阅读(878)  评论(0编辑  收藏  举报