首先需要创建serviceAccount:

apiVersion: v1
kind: ServiceAccount
metadata:
  name: test-sa
  namespace: test

接着需要创建相关的rbac:

apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRole
metadata:
  name: my-cluster
rules:
  - apiGroups: [""]
    resources: ["nodes"]
    verbs: ["get","list"]
---
apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRoleBinding
metadata:
  name: my-bind
subjects:
  - kind: ServiceAccount
    name: test-sa
    namespace: test
roleRef:
  kind: ClusterRole
  name: my-cluster
  apiGroup: rbac.authorization.k8s.io

最后在需要访问内置资源的pod里面加上serviceAccount:

apiVersion: v1
kind: Pod
metadata:
  name: testpod
  namespace: test
  labels:
    app: test
spec:
  containers:
    - name: app
      image: xxxx
  serviceAccountName: test-sa

serviceAccount所需要的证书会被mount到 

/var/run/secrets/kubernetes.io/serviceaccount

client-go的代码只需要

config,err := rest.InClusterConfig()
if err!=nil {
	panic(err)
}
client,err := kubernetes.NewForConfig(config)
if err!=nil {
	panic(err)
}

就可以访问到了。

Logo

K8S/Kubernetes社区为您提供最前沿的新闻资讯和知识内容

更多推荐