借用华为云官方的一个图,比较形象:
目录
配置Role通过RoleBinding绑定sa-example
通过RoleBinding指定角色并绑定ServiceAccount
ServiceAccount
ServiceAccount主要作用是pod和apiserver交互
创建账户
创建一个 ServiceAccount(默认命令空间default)
kubectl create serviceaccount sa-example
查看ServiceAccount
kubectl get sa
查看其token
kubectl describe sa sa-example
查看token对应Secret kubectl describe secret sa-example-token-r6jc7
创建pod并在pod内使用
创建pod,指定刚才创建的ServiceAccount (sa-example),编辑sa-pod.yaml
apiVersion: v1
kind: Pod
metadata:
name: sa-example
spec:
serviceAccountName: sa-example
containers:
- image: nginx:alpine
name: container-0
resources:
limits:
cpu: 100m
memory: 200Mi
requests:
cpu: 100m
memory: 200Mi
imagePullSecrets:
- name: default-secret
创建pod, kubectl create -f sa-pod.yaml
查看pod创建情况:kubectl describe pod sa-example
进入pod内部:kubectl exec -it sa-example -- /bin/sh
访问apiserver
export CURL_CA_BUNDLE=/var/run/secrets/kubernetes.io/serviceaccount/ca.crt
TOKEN=$(cat /var/run/secrets/kubernetes.io/serviceaccount/token)
curl -H "Authorization: Bearer $TOKEN" https://kubernetes
可以发现没有访问权限
配置Role通过RoleBinding绑定sa-example
k8s使用RBAC进行认证,下面是涉及到的四种资源
Role:角色,其实是定义一组对Kubernetes资源(命名空间级别)的访问规则。
RoleBinding:角色绑定,定义了用户和角色的关系。
ClusterRole:集群角色,其实是定义一组对Kubernetes资源(集群级别,包含全部命名空间)的访问规则。
ClusterRoleBinding:集群角色绑定,定义了用户和集群角色的关系。
创建Role并配置权限
配置在default下pod进行GET/LIST操作
kind: Role
apiVersion: rbac.authorization.k8s.io/v1
metadata:
namespace: default # 命名空间
name: role-example
rules:
- apiGroups: [""]
resources: ["pods"] # 可以访问pod
verbs: ["get", "list"] # 可以执行GET、LIST操作
通过RoleBinding指定角色并绑定ServiceAccount
kind: RoleBinding
apiVersion: rbac.authorization.k8s.io/v1
metadata:
name: rolebinding-example
namespace: default
subjects: # 指定用户
- kind: User # 普通用户
name: user-example
apiGroup: rbac.authorization.k8s.io
- kind: ServiceAccount # ServiceAccount
name: sa-example
namespace: default
roleRef:
kind: Role
name: role-example # 指定角色
apiGroup: rbac.authorization.k8s.io
讲上述两个RoleBinding.yaml合并成一步操作
kind: Role
apiVersion: rbac.authorization.k8s.io/v1
metadata:
namespace: default
name: role-example
rules:
- apiGroups: [""] # The API group "" indicates the core API Group.
resources: ["pods"]
verbs: ["get", "watch", "list"]
nonResourceURLs: []
---
kind: RoleBinding
apiVersion: rbac.authorization.k8s.io/v1
metadata:
name: rolebinding-example
namespace: default
subjects:
- kind: User # 普通用户
name: user-example
apiGroup: rbac.authorization.k8s.io
- kind: ServiceAccount # ServiceAccount
name: sa-example
namespace: default
roleRef:
kind: Role
name: role-example
apiGroup: rbac.authorization.k8s.io
在pod内再次访问发现已经拥有权限
参考ServiceAccount_云容器引擎 CCE_Kubernetes基础知识_认证与授权_华为云