Kubernetes入门学习-十七-RBAC

最近学习k8s遇到很多问题,建了一个qq群:153144292,交流devops、k8s、docker等

授权插件:Node,ABAC,RBAC,Webhook
Kubernetes的授权是基于插件形式的,其常用的授权插件有以下几种:
    Node(节点认证)
    ABAC(基于属性的访问控制)
    RBAC(基于角色的访问控制)
    Webhook(基于http回调机制的访问控制)
    
    RBAC:Role-based AC
    
    角色(role)
    许可(permission)
    让一个用户(Users)扮演一个角色(Role),角色拥有权限,从而让用户拥有这样的权限,随
后在授权机制当中,只需要将权限授予某个角色,此时用户将获取对应角色的权限,从而实现角色的
访问控制。

用户--角色--oper-->objects

定义角色role: 
    operations
    objects
    
rolebinding
    user account OR service account
    role

    基于角色的访问控制(Role-Based Access Control, 即”RBAC”)使用”rbac.authorization.k8s.io” API
Group实现授权决策,允许管理员通过Kubernetes API动态配置策略。

    在k8s的授权机制当中,采用RBAC的方式进行授权,其工作逻辑是把对对象的操作权限定义到一个角色当中,
再将用户绑定到该角色,从而使用户得到对应角色的权限。此种方式仅作用于名称空间当中,这是什么意思呢?
当User1绑定到Role角色当中,User1就获取了对该NamespaceA的操作权限,但是对NamespaceB是没有权限进行操
作的,如get,list等操作。

   另外,k8s为此还有一种集群级别的授权机制,就是定义一个集群角色(ClusterRole),对集群内的所有资
源都有可操作的权限,从而将User2,User3通过ClusterRoleBinding到ClusterRole,从而使User2、User3拥有
集群的操作权限。
    
k8s中资源分别属于两个级别:集群和名称空间
    role和rolebinding授予是在名称空间级别
    clusterrole和clusterrolebinding授予是在集群级别
以上都是k8s标准资源

    但是这里有2种绑定ClusterRoleBinding、RoleBinding。也可以使用RoleBinding去绑定ClusterRole。
当使用这种方式进行绑定时,用户仅能获取当前名称空间的所有权限。为什么这么绕呢??举例有10个名
称空间,每个名称空间都需要一个管理员,而该管理员的权限都是一致的。那么此时需要去定义这样的管
理员,使用RoleBinding就需要创建10个Role,这样显得更加繁重。为此当使用RoleBinding去绑定一个
ClusterRole时,该User仅仅拥有对当前名称空间的集群操作权限,换句话说,此时只需要创建一个
ClusterRole就解决了以上的需求。

这里要注意的是:RoleBinding仅仅对当前名称空间有对应的权限。
在RBAC API中,一个角色包含了一套表示一组权限的规则。 权限以纯粹的累加形式累积(没有”否定”的
规则)。角色可以由命名空间(namespace)内的Role对象定义,而整个Kubernetes集群范围内有效的角
色则通过ClusterRole对象实现。

1、User --> Rolebinding --> Role
 (1)角色的创建
一个Role对象只能用于授予对某一单一命名空间中资源的访问权限
[root@master ~]# kubectl create role -h 
Create a role with single rule.

Examples:
  # Create a Role named "pod-reader" that allows user to perform "get", "watch" and "list" on pods
  kubectl create role pod-reader --verb=get --verb=list --verb=watch --resource=pods
  
  # Create a Role named "pod-reader" with ResourceName specified
  kubectl create role pod-reader --verb=get --resource=pods --resource-name=readablepod --resource-name=anotherpod
  
  # Create a Role named "foo" with API Group specified
  kubectl create role foo --verb=get,list,watch --resource=rs.extensions
  
  # Create a Role named "foo" with SubResource specified
  kubectl create role foo --verb=get,list,watch --resource=pods,pods/status

Options:
      --allow-missing-template-keys=true: If true, ignore any errors in templates when a field or map key is missing in
the template. Only applies to golang and jsonpath output formats.
      --dry-run=false: If true, only print the object that would be sent, without sending it.
  -o, --output='': Output format. One of:
json|yaml|name|go-template|go-template-file|template|templatefile|jsonpath|jsonpath-file.
      --resource=[]: Resource that the rule applies to
      --resource-name=[]: Resource in the white list that the rule applies to, repeat this flag for multiple items
      --save-config=false: If true, the configuration of current object will be saved in its annotation. Otherwise, the
annotation will be unchanged. This flag is useful when you want to perform kubectl apply on this object in the future.
      --template='': Template string or path to template file to use when -o=go-template, -o=go-template-file. The
template format is golang templates [http://golang.org/pkg/text/template/#pkg-overview].
      --validate=true: If true, use a schema to validate the input before sending it
      --verb=[]: Verb that applies to the resources contained in the rule

Usage:
  kubectl create role NAME --verb=verb --resource=resource.group/subresource [--resource-name=resourcename] [--dry-run]
[options]
使用kubectl create进行创建角色,指定角色名称,--verb指定权限,--resource指定资源或者资源组,--dry-run单跑模式并不会创建
Use "kubectl options" for a list of global command-line options (applies to all commands).

使用--dry-run参数查看role清单定义
[root@master ~]# kubectl create role pods-reader --verb=get,list,watch --resource=pods --dry-run -o yaml
apiVersion: rbac.authorization.k8s.io/v1
kind: Role
metadata:
  creationTimestamp: null
  name: pods-reader
rules:
- apiGroups:       #对那些api组内的资源进行操作
  - ""
  resources:       #对那些资源定义
  - pods
  verbs:           #操作权限定义
  - get
  - list
  - watch
[root@master manifests]# kubectl create role pods-reader --verb=get,list,watch --resource=pods --dry-run -o yaml > role-demo.yaml
[root@master manifests]# vi role-demo.yaml 
[root@master manifests]# cat role-demo.yaml 
apiVersion: rbac.authorization.k8s.io/v1
kind: Role
metadata:
  name: pods-reader
  namespace: default
rules:
- apiGroups:
  - ""
  resources:
  - pods
  verbs:
  - get
  - list
  - watch
[root@master manifests]# kubectl apply -f role-demo.yaml 
role.rbac.authorization.k8s.io/pods-reader created
[root@master manifests]# kubectl get role
NAME          AGE
pods-reader   40s
[root@master manifests]# kubectl describe role pods-reader
Name:         pods-reader
Labels:       <none>
Annotations:  kubectl.kubernetes.io/last-applied-configuration:
                {"apiVersion":"rbac.authorization.k8s.io/v1","kind":"Role","metadata":{"annotations":{},"name":"pods-reader","namespace":"default"},"rules...
PolicyRule:
  Resources  Non-Resource URLs  Resource Names  Verbs
  ---------  -----------------  --------------  -----
  pods       []                 []              [get list watch]
  #此处已经定义了pods-reader这个角色对pods资源拥有get、list、watch的权限
  
(2)角色的绑定
RoleBinding可以引用在同一命名空间内定义的Role对象。
[root@master manifests]# kubectl create rolebinding -h
Create a RoleBinding for a particular Role or ClusterRole.

Examples:
  # Create a RoleBinding for user1, user2, and group1 using the admin ClusterRole
  kubectl create rolebinding admin --clusterrole=admin --user=user1 --user=user2 --group=group1

Options:
      --allow-missing-template-keys=true: If true, ignore any errors in templates when a field or map key is missing in
the template. Only applies to golang and jsonpath output formats.
      --clusterrole='': ClusterRole this RoleBinding should reference
      --dry-run=false: If true, only print the object that would be sent, without sending it.
      --generator='rolebinding.rbac.authorization.k8s.io/v1alpha1': The name of the API generator to use.
      --group=[]: Groups to bind to the role
  -o, --output='': Output format. One of:
json|yaml|name|go-template|go-template-file|template|templatefile|jsonpath|jsonpath-file.
      --role='': Role this RoleBinding should reference
      --save-config=false: If true, the configuration of current object will be saved in its annotation. Otherwise, the
annotation will be unchanged. This flag is useful when you want to perform kubectl apply on this object in the future.
      --serviceaccount=[]: Service accounts to bind to the role, in the format <namespace>:<name>
      --template='': Template string or path to template file to use when -o=go-template, -o=go-template-file. The
template format is golang templates [http://golang.org/pkg/text/template/#pkg-overview].
      --validate=true: If true, use a schema to validate the input before sending it

Usage:
  kubectl create rolebinding NAME --clusterrole=NAME|--role=NAME [--user=username] [--group=groupname]
[--serviceaccount=namespace:serviceaccountname] [--dry-run] [options]
使用kubectl create进行创建角色绑定,指定角色绑定的名称,--role|--clusterrole指定绑定哪个角色,--user指定哪个用户
Use "kubectl options" for a list of global command-line options (applies to all commands).
[root@master manifests]# kubectl create rolebinding wolf-read-pods --role=pods-reader --user=wolf --dry-run -o yaml > rolebinding-demo.yaml
[root@master manifests]# cat rolebinding-demo.yaml 
apiVersion: rbac.authorization.k8s.io/v1
kind: RoleBinding
metadata:
  creationTimestamp: null
  name: wolf-read-pods
roleRef:
  apiGroup: rbac.authorization.k8s.io
  kind: Role
  name: pods-reader
subjects:
- apiGroup: rbac.authorization.k8s.io
  kind: User
  name: wolf
#创建角色绑定
[root@master manifests]# kubectl apply -f rolebinding-demo.yaml     
rolebinding.rbac.authorization.k8s.io/wolf-read-pods created
#查看角色绑定的信息,这里可以看到user:magedu绑定到了pods-reader这个角色上
[root@master manifests]# kubectl describe rolebinding wolf-read-pods
Name:         wolf-read-pods
Labels:       <none>
Annotations:  kubectl.kubernetes.io/last-applied-configuration:
                {"apiVersion":"rbac.authorization.k8s.io/v1","kind":"RoleBinding","metadata":{"annotations":{},"creationTimestamp":null,"name":"wolf-read-...
Role:
  Kind:  Role
  Name:  pods-reader
Subjects:
  Kind  Name  Namespace
  ----  ----  ---------
  User  wolf  
  
切换wolf这个用户,并使用get获取pods资源信息
[root@master manifests]# kubectl config use-context wolf@kubernetes 
Switched to context "wolf@kubernetes".
[root@master manifests]# kubectl get pods
NAME                            READY   STATUS    RESTARTS   AGE
myapp-0                         1/1     Running   0          5d18h
myapp-1                         1/1     Running   0          5d18h
myapp-2                         1/1     Running   0          5d18h
myapp-3                         1/1     Running   0          5d18h
nginx-7849c4bbcd-dscjr          1/1     Running   0          22d
nginx-7849c4bbcd-vdd45          1/1     Running   0          22d
nginx-7849c4bbcd-wrvks          1/1     Running   0          22d
nginx-deploy-84cbfc56b6-scrnt   1/1     Running   0          5d19h
pod-sa-demo                     1/1     Running   0          4d18h
获取其他名称空间测试
[root@master manifests]#  kubectl get pods -n ingress-nginx
Error from server (Forbidden): pods is forbidden: User "wolf" cannot list resource "pods" in API group "" in the namespace "ingress-nginx"
从上面的操作,可以总结出,role的定义和绑定,仅作用于当前名称空间,在获取ingress-nginx名称空间时,一样会出现Forbidden!!!

2、User --> Clusterrolebinding --> Clusterrole
 (1)clusterrole定义
ClusterRole对象可以授予与Role对象相同的权限,但由于它们属于集群范围对象, 也可以使用它们授予对以下几种资源的访问权限:

集群范围资源(例如节点,即node)
非资源类型endpoint(例如”/healthz”)
跨所有命名空间的命名空间范围资源(例如pod,需要运行命令kubectl get pods --all-namespaces来查询集群中所有的pod)
先切换回kubernetes-admin
[root@master manifests]# kubectl config use-context kubernetes-admin@kubernetes
Switched to context "kubernetes-admin@kubernetes".
[root@master manifests]# kubectl create clusterrole cluster-read --verb=get,list,watch --resource=pods -o yaml > clusterrole-demo.yaml
[root@master manifests]# vim clusterrole-demo.yaml
[root@master manifests]# cat clusterrole-demo.yaml   #定义clusterrole和权限
apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRole
metadata:
  name: cluster-read
rules:
- apiGroups:
  - ""
  resources:
  - pods
  verbs:
  - get
  - list
  - watch
[root@master manifests]# kubectl apply -f clusterrole-demo.yaml
Warning: kubectl apply should be used on resource created by either kubectl create --save-config or kubectl apply
clusterrole.rbac.authorization.k8s.io/cluster-read configured
[root@master manifests]# kubectl get role
NAME          AGE
pods-reader   17m
[root@master manifests]# kubectl get clusterrole
NAME                                                                   AGE
admin                                                                  23d
cluster-admin                                                          23d
cluster-read                                                           3m42s

[root@master manifests]# useradd ik8s
[root@master ~]# cp -rp .kube/ /home/ik8s/
[root@master ~]# chown -R ik8s.ik8s /home/ik8s/
[root@master ~]# su - ik8s
[ik8s@master ~]$ kubectl config use-context wolf@kubernetes
Switched to context "wolf@kubernetes".
[ik8s@master ~]$ kubectl config view
apiVersion: v1
clusters:
- cluster:
    certificate-authority-data: DATA+OMITTED
    server: https://10.249.6.100:6443
  name: kubernetes
contexts:
- context:
    cluster: kubernetes
    user: kubernetes-admin
  name: kubernetes-admin@kubernetes
- context:
    cluster: kubernetes
    user: wolf
  name: wolf@kubernetes
current-context: wolf@kubernetes      这里当前用户为wolf
kind: Config
preferences: {}
users:
- name: kubernetes-admin
  user:
    client-certificate-data: REDACTED
    client-key-data: REDACTED
- name: wolf
  user:
    client-certificate-data: REDACTED
    client-key-data: REDACTED
    
(2)clusterrolebinding定义
[root@master manifests]# kubectl get rolebinding
NAME             AGE
wolf-read-pods   14m

删除之前的role
[root@master manifests]# kubectl delete rolebinding wolf-read-pods
rolebinding.rbac.authorization.k8s.io "wolf-read-pods" deleted
[root@master manifests]# kubectl get pods
NAME                            READY   STATUS    RESTARTS   AGE
myapp-0                         1/1     Running   0          5d19h
myapp-1                         1/1     Running   0          5d19h
myapp-2                         1/1     Running   0          5d18h
myapp-3                         1/1     Running   0          5d18h
nginx-7849c4bbcd-dscjr          1/1     Running   0          22d
nginx-7849c4bbcd-vdd45          1/1     Running   0          22d
nginx-7849c4bbcd-wrvks          1/1     Running   0          22d
nginx-deploy-84cbfc56b6-scrnt   1/1     Running   0          5d19h
pod-sa-demo                     1/1     Running   0          4d18h
-----------------
普通用户测试
[ik8s@master ~]$ kubectl get pods
Error from server (Forbidden): pods is forbidden: User "wolf" cannot list resource "pods" in API group "" in the namespace "default"

----------------
kubectl create clusterrolebinding wolf-read-all-pods --clusterrole=cluster-read --user=wolf --dry-run -o yaml > clusterrolebinding-demo.yaml
[root@master manifests]# kubectl create clusterrolebinding wolf-read-all-pods --clusterrole=cluster-read --user=wolf --dry-run -o yaml > clusterrolebinding-demo.yaml
[root@master manifests]# vim clusterrolebinding-demo.yaml
[root@master manifests]# cat clusterrolebinding-demo.yaml 
apiVersion: rbac.authorization.k8s.io/v1beta1
kind: ClusterRoleBinding
metadata:
  name: wolf-read-all-pods
roleRef:
  apiGroup: rbac.authorization.k8s.io
  kind: ClusterRole
  name: cluster-read
subjects:
- apiGroup: rbac.authorization.k8s.io
  kind: User
  name: wolf

[root@master manifests]# kubectl get clusterrolebinding
NAME                                                   AGE
。。。。
wolf-read-all-pods                                     3m14s
[root@master manifests]# kubectl describe clusterrolebinding wolf-read-all-pods
'Name:         wolf-read-all-pods
Labels:       <none>
Annotations:  kubectl.kubernetes.io/last-applied-configuration:
                {"apiVersion":"rbac.authorization.k8s.io/v1beta1","kind":"ClusterRoleBinding","metadata":{"annotations":{},"name":"wolf-read-all-pods"},"r...
Role:
  Kind:  ClusterRole
  Name:  cluster-read
Subjects:
  Kind  Name  Namespace
  ----  ----  ---------
  User  wolf  
----------------------------
在ik8s用户界面查看
[ik8s@master ~]$ kubectl get pods 
NAME                            READY   STATUS    RESTARTS   AGE
myapp-0                         1/1     Running   0          5d19h
myapp-1                         1/1     Running   0          5d19h
myapp-2                         1/1     Running   0          5d19h
myapp-3                         1/1     Running   0          5d19h
nginx-7849c4bbcd-dscjr          1/1     Running   0          22d
nginx-7849c4bbcd-vdd45          1/1     Running   0          22d
nginx-7849c4bbcd-wrvks          1/1     Running   0          22d
nginx-deploy-84cbfc56b6-scrnt   1/1     Running   0          5d19h
pod-sa-demo                     1/1     Running   0          4d18h
继续查看其他namespace
[ik8s@master ~]$  kubectl get pods -n ingress-nginx
NAME                                        READY   STATUS    RESTARTS   AGE
nginx-ingress-controller-797b884cbc-whphv   1/1     Running   0          11d

删除试试
[ik8s@master ~]$ kubectl delete pods pod-sa-demo
Error from server (Forbidden): pods "pod-sa-demo" is forbidden: User "wolf" cannot delete resource "pods" in API group "" in the namespace "default"
从上面的实验,我们可以知道对用户wolf进行集群角色绑定,用户wolf将会获取对集群内所有资源的对应权限。

 3、User --> Rolebinding --> Clusterrole
将wolf通过rolebinding到集群角色wolf-read-pods当中,此时,wolf仅作用于当前名称空间的所有pods资源的权限
kubectl create rolebinding wolf-read-pods --clusterrole=cluster-read --user=wolf --dry-run -o yaml > rolebinding-clusterrole-demo.yaml
[root@master manifests]# kubectl create rolebinding wolf-read-pods --clusterrole=cluster-read --user=wolf --dry-run -o yaml > rolebinding-clusterrole-demo.yaml
[root@master manifests]# vim rolebinding-clusterrole-demo.yaml
[root@master manifests]# cat rolebinding-clusterrole-demo.yaml 
apiVersion: rbac.authorization.k8s.io/v1
kind: RoleBinding
metadata:
  name: wolf-read-pods
  namespace: default
roleRef:
  apiGroup: rbac.authorization.k8s.io
  kind: ClusterRole
  name: cluster-read
subjects:
- apiGroup: rbac.authorization.k8s.io
  kind: User
  name: wolf
[root@master manifests]# kubectl apply -f rolebinding-clusterrole-demo.yaml
rolebinding.rbac.authorization.k8s.io/wolf-read-pods created

------------
[ik8s@master ~]$ kubectl get pods
NAME                            READY   STATUS    RESTARTS   AGE
myapp-0                         1/1     Running   0          5d19h
myapp-1                         1/1     Running   0          5d19h
myapp-2                         1/1     Running   0          5d19h
myapp-3                         1/1     Running   0          5d19h
nginx-7849c4bbcd-dscjr          1/1     Running   0          22d
nginx-7849c4bbcd-vdd45          1/1     Running   0          22d
nginx-7849c4bbcd-wrvks          1/1     Running   0          22d
nginx-deploy-84cbfc56b6-scrnt   1/1     Running   0          5d19h
pod-sa-demo                     1/1     Running   0          4d19h
[ik8s@master ~]$ kubectl get pods -n ingress-nginx
Error from server (Forbidden): pods is forbidden: User "wolf" cannot list resource "pods" in API group "" in the namespace "ingress-nginx"

==============
RBAC的三种授权访问
RBAC不仅仅可以对user进行访问权限的控制,还可以通过group和serviceaccount进行访问权限控制。当我们想对一组用户进行权限分配时,即可将这一组用户归并到一个组内,从而通过对group进行访问权限的分配,达到访问权限控制的效果。
从前面serviceaccount我们可以了解到,Pod可以通过 spec.serviceAccountName来定义其是以某个serviceaccount的身份进行运行,当我们通过RBAC对serviceaccount进行访问授权时,即可以实现Pod对其他资源的访问权限进行控制。也就是说,当我们对serviceaccount进行rolebinding或clusterrolebinding,会使创建Pod拥有对应角色的权限和apiserver进行通信。

pod--(spec:   serviceAccountName: xxx)---->Serviceaccount-->Rolebinding-->role

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值