pod容器中的进程调用kunbernetes的api server 权限配置
背景:开发一个服务需要调用kunbernetes的api server ,需要一些认证信息,使用RBAC(基于角色的访问控制)
1. 先创建一个clusterrole ,限定可以操作的范围
kubectl -f apply clusterrole.yaml
clusterrole.yaml
apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRole
metadata:
name: protal-demo
rules:
- apiGroups:
- ""
resources:
- pods
- pods/log
- pods/exec
- services
verbs:
- get
- list
- watch
- delete
- create
- update
- patch
- apiGroups:
- extensions
resources:
- deployments
- deployments/status
verbs:
- get
- list
- watch
- delete
- create
- update
- patch
- apiGroups:
- "apps"
resources:
- deployments
- replicasets
- pods
- pods/exec
verbs:
- get
- list
- watch
- delete
- create
- update
- patch
2. 创建需要在deployment中配置的serviceAccount,不配置会绑定默认default,apply之后会自动创建secret
kubectl -f apply serviceaccount.yaml
serviceaccount.yaml
apiVersion: v1
kind: ServiceAccount
metadata:
name: protal-demo
3. 创建ClusterRoleBinding ,将clusterrole跟sa绑定在一起
- ClusterRoleBinding在整个集群级别和所有namespaces将特定的subject与ClusterRole绑定,授予权限。
apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRoleBinding
metadata:
name: protal-demo
roleRef:
apiGroup: rbac.authorization.k8s.io
kind: ClusterRole
name: protal-demo
subjects:
- kind: ServiceAccount
name: protal-demo // 要绑定的sa
4. 在自己的deployment yaml文件中添加, pod 会挂载新的secret,创建sa账号的时候会自动创建相应的secret
serviceAccount: protal-demo
serviceAccountName: protal-demo
最终describe pod时候可以看到挂载到新的secret上,即完成了一系列绑定,再次访问服务就不会报403了
Mounts:
/var/run/secrets/kubernetes.io/serviceaccount from protal-demo-token-96g56 (ro)
Volumes:
protal-demo-token-96g56:
Type: Secret (a volume populated by a Secret)
SecretName: protal-demo-token-96g56
Optional: false