创建命名空间

或者使用已有的命令空间

kubectl create ns myns

创建serviceaccount

名称为mysc,命名空间为myns,此命令会在当前的名字空间中生成一个 服务账号和一个与之关联的 Secret

kubectl create serviceaccount mysc -n myns

查看Secret

kubectl get serviceaccount -n myns mysc -o yaml

使用RBAC赋权

创建Role

定义访问资源的权限,rules参考使用 RBAC 鉴权 | Kubernetes

apiVersion: rbac.authorization.k8s.io/v1
kind: Role
metadata:
  namespace: myns
  name: mysc-role
rules:
- apiGroups: [""] # "" 标明 core API 组
  resources: ["pods"]
  verbs: ["list", "create"]

创建RoleBinding

将serviceaccount与Role绑定,subjects使用参考使用 RBAC 鉴权 | Kubernetes

apiVersion: rbac.authorization.k8s.io/v1
kind: RoleBinding
metadata:
  name: my-rolebinding
  namespace: myns
subjects:
- kind: ServiceAccount
  name: mysc
roleRef:
  kind: Role
  name: mysc-role
  apiGroup: rbac.authorization.k8s.io

获取TOKEN和APISERVER

export TOKEN=$(kubectl describe secrets -n myns $(kubectl -n myns get secret | awk '/mysc/{print $1}')|awk '{printf("%s\n", $2)}' |tail -1| awk '{printf("%s", $1)}')
export APISERVER=$(kubectl config view |grep server|cut -f 2- -d ":" | tr -d " ")

使用token获取资源

注意,需要加-H "Authorization: Bearer $TOKEN"请求头,api可在Kubernetes API Reference Docs获取

curl -H "Authorization: Bearer $TOKEN" ${APISERVER}/api/v1/namespaces/myns/pods -k

使用ClusterRole

apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRole
metadata:
  name: mysc-clusterrole
rules:
- apiGroups: [""] # "" 标明 core API 组
  resources: ["pods"]
  verbs: ["list", "create"]

---
apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRoleBinding
metadata:
  name: my-clusterrolebinding   //不加namespace,会被忽略,因为 ClusterRoles 不受名字空间限制
subjects:
- kind: ServiceAccount
  name: mysc
  namespace: myns    //在metadata中没加namespace,因此在此处需要加上,不然没法找到mysc
roleRef:
  kind: ClusterRole
  name: mysc-clusterrole
  apiGroup: rbac.authorization.k8s.io

此时可获取除myns命名空间的资源 

curl -H "Authorization: Bearer $TOKEN" ${APISERVER}/api/v1/namespaces/default/pods -k

Role和ClusterRole的区别

使用 RBAC 鉴权 | Kubernetes

ClusterRole示例

使用 RBAC 鉴权 | Kubernetes

ClusterRoleBinding示例

使用 RBAC 鉴权 | Kubernetes

Logo

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

更多推荐