Kubernetes RBAC 之 ServiceAccount
RABC 英文全称是 Role-Based Access Control,它通过角色绑定账户,来使得账户拥有某些操控 K8S 集群的权限。ServiceAccount 是集群内部 Pod 访问集群所使用的服务账户,它包括了 Namespace、Token、Ca 证书,并且通过目录挂载的方式绑定 Pod。当 Pod 运行起来的时候,就会使用这些信息与 ApiServer 进行通信。
·
Kubernetes RBAC 之 ServiceAccount
定义
RABC 英文全称是 Role-Based Access Control,它通过角色绑定账户,来使得账户拥有某些操控 K8S 集群的权限。ServiceAccount 是集群内部 Pod 访问集群所使用的服务账户,它包括了 Namespace、Token、Ca 证书,并且通过目录挂载的方式绑定 Pod。当 Pod 运行起来的时候,就会使用这些信息与 ApiServer 进行通信。
使用
-
创建 sa 账户 sa-test
kubectl create sa sa-test
-
创建绑定 sa-test 账户的 Pod
apiVersion: v1 kind: Pod metadata: name: rbac-sa namespace: default labels: app: nginx spec: serviceAccountName: sa-test containers: - name: curl-nginx ports: - containerPort: 80 image: curl-nginx:1.0 imagePullPolicy: IfNotPresent
-
访问新建立 Pod,发现没有权限访问 ApiServer
root@k8s-master1:~# kubectl exec -it rbac-sa -- /bin/sh / # cd /var/run/secrets/kubernetes.io/serviceaccount/ /var/run/secrets/kubernetes.io/serviceaccount # ls -l total 0 lrwxrwxrwx 1 root root 13 Jul 6 02:59 ca.crt -> ..data/ca.crt lrwxrwxrwx 1 root root 16 Jul 6 02:59 namespace -> ..data/namespace lrwxrwxrwx 1 root root 12 Jul 6 02:59 token -> ..data/token /var/run/secrets/kubernetes.io/serviceaccount # curl --cacert ./ca.crt -H "Authorization: Bearer $(cat ./token)" https://kubernetes/api/v1/namespaces/kube-system { "kind": "Status", "apiVersion": "v1", "metadata": {}, "status": "Failure", "message": "namespaces \"kube-system\" is forbidden: User \"system:serviceaccount:default:sa-test\" cannot get resource \"namespaces\" in API group \"\" in the namespace \"kube-system\"", "reason": "Forbidden", "details": { "name": "kube-system", "kind": "namespaces" }, "code": 403 } /var/run/secrets/kubernetes.io/serviceaccount #
-
赋予 sa-test 权限
root@k8s-master1:~# kubectl create clusterrolebinding sa-test-admin --clusterrole=cluster-admin --serviceaccount=default:sa-test clusterrolebinding.rbac.authorization.k8s.io/sa-test-admin created
-
再次访问
root@k8s-master1:~# kubectl exec -it rbac-sa -- /bin/sh / # curl --cacert ./ca.crt -H "Authorization: Bearer $(cat ./token)" https://kubernetes/api/v1/namespaces/kube-system /var/run/secrets/kubernetes.io/serviceaccount # curl --cacert ./ca.crt -H "Authorization: Bearer $(cat ./token)" https://kubernetes/api/v1/namespaces/kube-system { "kind": "Namespace", "apiVersion": "v1", "metadata": { "name": "kube-system", "uid": "6a42a1bb-6375-4658-9948-7f395e509197", "resourceVersion": "26", "creationTimestamp": "2024-05-13T00:41:10Z", "labels": { "kubernetes.io/metadata.name": "kube-system" }, "managedFields": [ { "manager": "kube-apiserver", "operation": "Update", "apiVersion": "v1", "time": "2024-05-13T00:41:10Z", "fieldsType": "FieldsV1", "fieldsV1": { "f:metadata": { "f:labels": { ".": {}, "f:kubernetes.io/metadata.name": {} } } } } ] }, "spec": { "finalizers": [ "kubernetes" ] }, "status": { "phase": "Active" } }/var/run/secrets/kubernetes.io/serviceaccount #
更多推荐
已为社区贡献2条内容
所有评论(0)