java 呼叫 k8s 的 apiserver

BUG弄潮儿發表於2024-10-19

建立serviceaccount

serviceaccount.yaml

apiVersion: v1
kind: ServiceAccount
metadata:
  name: myadmin
  namespace: default

建立叢集角色ClusterRole

clusterrole.yaml

apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRole
metadata:
  name: my-clusterrole
rules:
- apiGroups: ["*"]
  resources: ["*"]
  verbs: ["*"]

建立叢集角色繫結ClusterRoleBinding

clusterrolebinding.yaml

apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRoleBinding
metadata:
  name: my-clusterrolebinding
subjects:
# 此叢集角色繫結允許 "my-group-manager" 組中的任何人訪問任何名字空間中的 Secret 資源
- kind: Group
  name: my-group-manager
  apiGroup: rbac.authorization.k8s.io
- kind: ServiceAccount
  name: myadmin
  namespace: default
roleRef:
  kind: ClusterRole
  name: my-clusterrole
  apiGroup: rbac.authorization.k8s.io

獲取apiserver的地址

https://cloud.tencent.com/developer/article/2242229

kubectl cluster-info

獲取tonken:https://www.cnblogs.com/lori/p/18380527

kubectl proxy --port=8001
curl 'http://127.0.0.1:8001/api/v1/namespaces/default/serviceaccounts/myadmin/token' \
  -H "Content-Type:application/json" -X POST -d '{}'

default為namespace名;myadmin為serviceaccount名

或者

kubectl -n default create token myadmin

建立永久token

apiVersion: v1
kind: Secret
metadata:
  name: admin-token
  namespace: default
  annotations:
    kubernetes.io/service-account.name: "myadmin"   
type: kubernetes.io/service-account-token  
kubectl get secret admin-token -n default -o jsonpath={".data.token"} | base64 -d
curl -H "Authorization: Bearer eyJhbGciOiJSUzI1NiIsImtpZCI6ImQ4Slh0Mk9lMzd0TXNlZW9sbGRRMUVfRWtYSHVnNnFwMG11TmhYR3dWM2cifQ.eyJhdWQiOlsiaHR0cHM6Ly9rdWJlcm5ldGVzLmRlZmF1bHQuc3ZjLmNsdXN0ZXIubG9jYWwiXSwiZXhwIjoxNzI5MTM4NzExLCJpYXQiOjE3MjkxMzUxMTEsImlzcyI6Imh0dHBzOi8va3ViZXJuZXRlcy5kZWZhdWx0LnN2Yy5jbHVzdGVyLmxvY2FsIiwia3ViZXJuZXRlcy5pbyI6eyJuYW1lc3BhY2UiOiJkZWZhdWx0Iiwic2VydmljZWFjY291bnQiOnsibmFtZSI6Im15YWRtaW4iLCJ1aWQiOiIxNzQ2YzY1Yy00ZjVlLTQ5ODMtYWJmOS1kZjM5NzkzNGI0ZTgifX0sIm5iZiI6MTcyOTEzNTExMSwic3ViIjoic3lzdGVtOnNlcnZpY2VhY2NvdW50OmRlZmF1bHQ6bXlhZG1pbiJ9.Se3DvijQSXeP8tfJ6bdp_97TKvD1FSS3NkRcU5IO6ZcXhuodhPCfR7X9k6oDjwNYXuhW4v3rIYLSR5C79K_lwVWWKFxNAfkMXgl_gGu0CeIJdMOaO2vTOHAc8vqr1SWmw9NhX6oIqPfgDCCVBKtpEog43VbPKRniDVGEn2MAbrXf6qb0uncIYfzk9hJ4zo14-fM_6VPaW-PmKl5PgbfsZFY9B8nQW9G4ivEjQLQMV3VLB5shdf8JDVJYJL_EQT9skO8fmLomCnF5s02XMDAzmtILGGhummLk0prIqbLUyNUOCfkuUKAwatse51Qup7itFPiATzmRcmsGE5DhnSevzQ" https://10.0.2.11:6443/api/v1/namespaces/kube-system/services -k

-k忽略https的證書校驗

參考

https://www.cnblogs.com/niuben/p/18408731
https://www.cnblogs.com/lori/p/18380527
https://kubernetes.io/zh-cn/docs/reference/access-authn-authz/authentication/
https://kubernetes.io/zh-cn/docs/reference/access-authn-authz/rbac/
https://blog.csdn.net/fly910905/article/details/101345091

相關文章