k8s基础入门之RBAC实战

1 RBAC相关概念

RBAC是基于角色的访问控制 (Role-Based Access Control) 在RBAC中,权限与角色相关联。Kubernetes 基于角色的访问控制使用rbac.authorization.k8s.io API组来实现权限控制,RBAC允许管理员通过Kubernetes API动态的配置权限策略。如果需要开启RBAC授权需要在apiserver组件中指定--authorization-mode=Node,RBAC k8s安全控制框架主要由3个阶段进行控制 authentication(鉴权) authorization(授权) adimission control(准入控制) Kubernetes的用户分为两种:User Account,用户账号,给Kubernetes操作人员使用的账号;Service Account,服务账号,给Kubernetes中Pod使用的账号。Kubernetes管理员查看和操作Kubernetes对象都是通过User Account 账号实现,而Pod去访问集群中的资源时使用的是Service Account。Kubernetes中一切皆对象,权限其实是对特定对象操作,如对某个名称空间中Pod的 GET/DELETE/POST 等操作。 不同的权限就是不同Permission的集合,将权限关联到Role上,再通过RoleBinding关联账户和权限,这就是RBAC实现方式。 k8s基础入门之RBAC实战

不同类型的授权方式
Role和RoleBinding属于名称空间资源,而Cluster和ClusterRoleBinding是集群层面的资源,Kubernetes允许三种绑定权限的方式(如图):
• RoleBinding 关联 Role 和 User
User 具备当前NameSpace空间中的权限,不具备跨名称空间权限
• RoleBinding 关联 ClusterRole 和 User
ClusterRole权限降级,只能对当前名称空间中的资源具备权限,不具备跨名称空间的权限。该方式的意义在于:对不同名称空间管理员授权时,只需要定义一个ClusterRole即可,不需要定义多个基于名称空间的Role
• ClusterRoleBinding 关联 ClusterRole 和 User
User 具备集群级别权限,可以跨名称空间操作资源对象

k8s基础入门之RBAC实战

1.2 Role RoleBinding ClusterRole ClusterRoleBinding ServiceAccount用法

Role
apiVersion: rbac.authorization.k8s.io/v1
kind: Role
metadata:
    name            <string>                # 在一个名称空间不能重复
    namespace       <string>                # 指定名称空间,默认defalut
    labels          <map[string]string>     # 标签
    annotations     <map[string]string>     # 注释
rules:              <[]Object               # role权限
    resources       <[]string>              # 指定资源名称资源对象列表
    apiGroups       <[]string>              # 指定API资源组
    resourceNames   <[]string>              # 指定具体资源的白名单,默认允许所有
    nonResourceURLs <[]string>              # 一种特殊的k8s对象
    verbs           <[]string> -required-   # 权限列表(actions)

ClusterRole
apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRole
metadata:
    name            <string>                        # 在一个集群内不能重复
    labels          <map[string]string>             # 标签
    annotations     <map[string]string>             # 注释
rules               <[]Object                       # 定义权限
    resources       <[]string>                      # 指定资源名称资源对象列表
    apiGroups       <[]string>                      # 指定API资源组
    resourceNames   <[]string>                      # 指定具体资源的白名单,默认允许所有
    nonResourceURLs <[]string>                      # 一种特殊的k8s对象
    verbs           <[]string> -required-           # 权限列表(actions)
aggregationRule     <Object>                        # 定义聚合规则
    clusterRoleSelectors    <[]Object>              # 集群角色选择器
        matchLabels         <map[string]string>     # key/value 选择器
        matchExpressions    <[]Object>              # 表达式选择器,参考 deployment.spec.selector

RoleBinding
apiVersion: rbac.authorization.k8s.io/v1
kind: RoleBinding
metadata:
    name            <string>                # 在一个名称空间不能重复
    namespace       <string>                # 指定名称空间,默认defalut
    labels          <map[string]string>     # 标签
    annotations     <map[string]string>     # 注释
roleRef             <Object> -required-     # 待绑定的角色
    kind            <string> -required-     # 资源类型
    name            <string> -required-     # 资源名称
    apiGroup        <string> -required-     # 资源组的APIGroup
subjects            <[]Object>              # 账户
    apiGroup        <string>                # 账户的api组名
        # "" 空字串表示serviceAccount
        # rbac.authorization.k8s.io 表示User或者Group
    kind            <string> -required-     # 账户类型,如User/Group/serviceAccount
    name            <string> -required-     # 账户名称
    namespace       <string>                # 账户的名称空间

ClusterRoleBinding
apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRoleBinding
metadata:
    name            <string>                # 在一个集群内不能重复
    labels          <map[string]string>     # 标签
    annotations     <map[string]string>     # 注释
roleRef             <Object> -required-     # 待绑定的角色
    kind            <string> -required-     # 资源类型
    name            <string> -required-     # 资源名称
    apiGroup        <string> -required-     # 资源组的APIGroup
subjects            <[]Object>              # 账户
    apiGroup        <string>                # 账户的api组名
        # "" 空字串表示serviceAccount
        # rbac.authorization.k8s.io 表示User或者Group
    kind            <string> -required-     # 账户类型,如User/Group/serviceAccount
    name            <string> -required-     # 账户名称
    namespace       <string>                # 账户的名称空间

ServiceAccount
# 一般只需要指定serviceaccount的名称即可
# 除了基础字段之外的其它字段很少使用,需要时手动查询
apiVersion: v1
kind: ServiceAccount        
metadata
    name            <string>                # 在一个名称空间不能重复
    namespace       <string>                # 指定名称空间,默认defalut
    labels          <map[string]string>     # 标签
    annotations     <map[string]string>     # 注释

1.3 RBAC API对象

Kubernetes有一个很基本的特性就是它的所有资源对象都是模型化的 API 对象,允许执行 CRUD(Create、Read、Update、Delete)操作(也就是我们常说的增、删、改、查操作),比如下面的这下资源:

    Pods
    ConfigMaps
    Deployments
    Nodes
    Secrets
    Namespaces

上面这些资源对象的可能存在的操作有:
    create
    get
    delete
    list
    update
    edit
    watch
    exec

2 RBAC使用演示

2.1 创建一个User Account

创建一个User Account来演示RBAC
创建user account 方法一:
安装cfssl
wget https://pkg.cfssl.org/R1.2/cfssl_linux-amd64
wget https://pkg.cfssl.org/R1.2/cfssljson_linux-amd64
wget https://pkg.cfssl.org/R1.2/cfssl-certinfo_linux-amd64
chmod +x cfssl_linux-amd64
mv cfssl_linux-amd64 /usr/local/bin/cfssl
chmod +x cfssljson_linux-amd64
mv cfssljson_linux-amd64 /usr/local/bin/cfssljson
chmod +x cfssl-certinfo_linux-amd64
mv cfssl-certinfo_linux-amd64 /usr/local/bin/cfssl-certinfo

cd /root/rbac
签发客户端证书
 cat > ca-config.json <<EOF
{
  "signing": {
    "default": {
      "expiry": "87600h"
    },
    "profiles": {
      "kubernetes": {
        "usages": [
            "signing",
            "key encipherment",
            "server auth",
            "client auth"
        ],
        "expiry": "87600h"
      }
    }
  }
}
EOF

 cat > suixiaofeng-csr.json <<EOF
{
  "CN": "suixiaofeng",
  "hosts": [],
  "key": {
    "algo": "rsa",
    "size": 2048
  },
  "names": [
    {
      "C": "CN",
      "ST": "BeiJing",
      "L": "BeiJing",
      "O": "k8s",
      "OU": "System"
    }
  ]
}
EOF

cfssl gencert -ca=ca.crt -ca-key=ca.key -config=ca-config.json -profile=kubernetes suixiaofeng-csr.json | cfssljson -bare suixiaofeng

查看生成的客户端证书
[root@k8s-master01 rbac]# ll suixiaofeng*
-rw-r--r-- 1 root root  224 5月  25 16:43 suixiaofeng-csr.json
-rw------- 1 root root 1679 5月  25 16:57 suixiaofeng-key.pem
-rw-r--r-- 1 root root 1241 5月  25 16:57 suixiaofeng.pem

创建user account 方法二:
生成私钥文件,并将文件放置于/etc/kubernetes/pki/专用目录中
[root@k8s-master01 2]# openssl genrsa -out suixiaofeng.key 2048
创建证书签署请求,-subj选项中CN的值将被kubeconfig作为用户名使用,O的值将被识别为用户组
openssl req -new -key suixiaofeng.key -out suixiaofeng.csr -subj "/CN=suixiaofeng/O=devopstack"
基于kubeadm安装Kubernetes集群时生成的CA签署证书,这里设置其有效时长为3650天:
openssl x509 -req -in suixiaofeng.csr -CA /etc/kubernetes/pki/ca.crt -CAkey /etc/kubernetes/pki/ca.key -CAcreateserial -out suixiaofeng.crt -days 3650
Signature ok
subject=/CN=suixiaofeng/O=devopstack
Getting CA Private Key

查看suixiaofeng客户端证书
[root@k8s-master01 2]# ll
总用量 12
-rw-r--r-- 1 root root 1009 5月  25 17:39 suixiaofeng.crt
-rw-r--r-- 1 root root  924 5月  25 17:35 suixiaofeng.csr
-rw-r--r-- 1 root root 1679 5月  25 17:30 suixiaofeng.key

生成config文件
配置集群参数
kubectl config set-cluster kubernetes \
  --server=https://192.168.10.71:6443 \
  --certificate-authority=/etc/kubernetes/pki/ca.crt \
  --embed-certs=true \
  --kubeconfig=suixiaofeng.kubeconfig

设置客户端认证

kubectl config set-credentials suixiaofeng \
  --client-certificate=/etc/kubernetes/pki/suixiaofeng.pem \
  --client-key=/etc/kubernetes/pki/suixiaofeng-key.pem \
  --embed-certs=true \
  --kubeconfig=suixiaofeng.kubeconfig

设置默认上下文
kubectl config set-context kubernetes \
  --cluster=kubernetes \
  --user=suixiaofeng \
  --kubeconfig=suixiaofeng.kubeconfig

设置当前使用配置
kubectl config use-context kubernetes --kubeconfig=suixiaofeng.kubeconfig

查看suixiaofeng用户有没有权限访问pod
[root@k8s-master01 rbac]# kubectl --kubeconfig=suixiaofeng.kubeconfig get pods
Error from server (Forbidden): pods is forbidden: User "suixiaofeng" cannot list resource "pods" in API group "" in the namespace "default"

切换至admin用户
kubectl config use-context kubernetes-admin@kubernetes
[root@k8s-master01 rbac]# kubectl get pods
NAME                                      READY   STATUS    RESTARTS   AGE
busybox                                   1/1     Running   95         32d
hostpathtest                              1/1     Running   3          47d
nfs-client-provisioner-794b747b95-27xmj   1/1     Running   1          33d
nginx-0                                   1/1     Running   1          32d
nginx-1                                   1/1     Running   1          32d
nginx-2                                   1/1     Running   1          32d
nginx-f89759699-thxcl                     1/1     Running   4          61d
nginx-statefulset-0                       1/1     Running   1          32d
可以看出有权限

2.2 创建Role

用户创建完成后,接下来就需要给该用户添加操作权限,我们来定义一个YAML文件,创建一个允许用户操作 查看Pod的角色,如下定义:(suixiaofeng-role.yaml)
[root@k8s-master01 rbac]# cat pod-read.yaml 
apiVersion: rbac.authorization.k8s.io/v1
kind: Role
metadata:
  name: pod-reader
  namespace: default

rules:

- apiGroups: [""]  # 组
  resources: ["pods"] #资源
  verbs: [ "watch", "list", "get"] #权限
[root@k8s-master01 rbac]# kubectl apply -f pod-read.yaml 
role.rbac.authorization.k8s.io/pod-reader created

2.3 创建角色权限绑定

[root@k8s-master01 rbac]# cat pod-read-bind.yaml
 apiVersion: rbac.authorization.k8s.io/v1
 kind: RoleBinding
 metadata:
   name: read-pods-bind
   namespace: default
 subjects:
 - kind: User
   name: suixiaofeng # 目标用户
   apiGroup: rbac.authorization.k8s.io
 roleRef:
   kind: Role
   name: pod-reader # 角色信息
   apiGroup: rbac.authorization.k8s.io

[root@k8s-master01 rbac]# kubectl apply -f pod-read-bind.yaml 
rolebinding.rbac.authorization.k8s.io/read-pods-bind created
验证
[root@k8s-master01 rbac]# kubectl --kubeconfig=suixiaofeng.kubeconfig get pods
NAME                                      READY   STATUS    RESTARTS   AGE
busybox                                   1/1     Running   95         32d
hostpathtest                              1/1     Running   3          47d
nfs-client-provisioner-794b747b95-27xmj   1/1     Running   1          33d
nginx-0                                   1/1     Running   1          32d
nginx-1                                   1/1     Running   1          32d
nginx-2                                   1/1     Running   1          32d
nginx-f89759699-thxcl                     1/1     Running   4          61d

如下 suixiaofeng有查看pod的权限了
[root@k8s-master01 rbac]# kubectl --kubeconfig=suixiaofeng.kubeconfig get cs
Error from server (Forbidden): componentstatuses is forbidden: User "suixiaofeng" cannot list resource "componentstatuses" in API group "" at the cluster scope

因为没有赋予其他权限 所以如上无权限

添加用户services权限
[root@k8s-master01 rbac]# cat pod-read.yaml 
apiVersion: rbac.authorization.k8s.io/v1
kind: Role
metadata:
  name: pod-reader
  namespace: default

rules:

- apiGroups: [""]
  resources: ["pods","services"]
  verbs: [ "watch", "list", "get"]

[root@k8s-master01 rbac]# kubectl --kubeconfig=suixiaofeng.kubeconfig   get svc
Error from server (Forbidden): services is forbidden: User "suixiaofeng" cannot list resource "services" in API group "" in the namespace "default"
[root@k8s-master01 rbac]# vim pod-read.yaml 
[root@k8s-master01 rbac]# kubectl apply -f pod-read.yaml 
role.rbac.authorization.k8s.io/pod-reader configured
[root@k8s-master01 rbac]# kubectl --kubeconfig=suixiaofeng.kubeconfig   get svc
NAME           TYPE        CLUSTER-IP       EXTERNAL-IP   PORT(S)        AGE
headless-svc   ClusterIP   None             <none>        80/TCP         33d
kubernetes     ClusterIP   10.96.0.1        <none>        443/TCP        166d
svc1           ClusterIP   10.110.207.5     <none>        8080/TCP       77d

2.4 ClusterRole和ClusterRoleBinding

Rule:规则,一组属于不同API Group的操作集合,Role:角色,用于定义一组对Kubernetes API对象操作的一组规则,作用于当个namespace;ClusterRole:集群角色,该角色不受namespace的限制;RoleBinding:将角色和被作用者进行绑定,作用于当个namespace;ClusterRoleBinding:将集群角色和作用者进行绑定,不受namespace限制;
[root@k8s-master01 rbac]# kubectl --kubeconfig=suixiaofeng.kubeconfig   get pod --all-namespaces
Error from server (Forbidden): pods is forbidden: User "suixiaofeng" cannot list resource "pods" in API group "" at the cluster scope
因为我们创建的用户只做了基于当前命名空间的权限,所以无法访问所有命名空间的权限.
如下操作授权,不受命名空间限制
ClusterRole创建:
 cat pod-read-ClusterRole.yaml
apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRole
metadata:
  name: ClusterRole-demo

rules:

- apiGroups: [""]
  resources: ["pods","services"]
  verbs: [ "watch", "list", "get"]

ClusterRoleBinding创建:
[root@k8s-master01 rbac]# kubectl apply -f pod-read-ClusterRoleBinding.yaml
clusterrolebinding.rbac.authorization.k8s.io/read-pods-ClusterRoleBinding-demo created
[root@k8s-master01 rbac]# cat pod-read-ClusterRoleBinding.yaml
 apiVersion: rbac.authorization.k8s.io/v1
 kind: ClusterRoleBinding
 metadata:
   name: read-pods-ClusterRoleBinding-demo
 subjects:
 - kind: User
   name: suixiaofeng # 目标用户
   apiGroup: rbac.authorization.k8s.io
 roleRef:
   kind: ClusterRole
   name: ClusterRole-demo # 角色信息
   apiGroup: rbac.authorization.k8s.io

验证是否可以查看所有命名空间的pod
[root@k8s-master01 rbac]# kubectl --kubeconfig=suixiaofeng.kubeconfig   get pod --all-namespaces
NAMESPACE              NAME                                         READY   STATUS    RESTARTS   AGE
default                busybox                                      1/1     Running   98         33d
default                hostpathtest                                 1/1     Running   3          48d
default                nfs-client-provisioner-794b747b95-27xmj      1/1     Running   1          34d
default                nginx-0                                      1/1     Running   1          33d
default                nginx-1                                      1/1     Running   1          33d
default                nginx-2                                      1/1     Running   1          33d
default                nginx-f89759699-thxcl                        1/1     Running   4          63d
default                nginx-statefulset-0                          1/1     Running   1          33d
default                nginx-statefulset-1                          1/1     Running   1          34d
default                nginx-statefulset-2                          1/1     Running   1          34d
default                nginx-statefulset-pod-0                      1/1     Running   1          34d
default                nginx-statefulset-pod-1                      1/1     Running   1          34d
default                nginx-statefulset-pod-2                      1/1     Running   1          34d
default                svc1-5ff98455f6-wrnvh                        1/1     Running   4          63d
default                svc2-678c5fb65-jpb7p                         1/1     Running   4          63d
default                svc3-55569d594-zthd8                         1/1     Running   4          63d
default                test-demo-configmap-vloume                   1/1     Running   167        62d
default                web-65b7447c7-cghzq                          1/1     Running   4          62d
ingress-nginx          nginx-ingress-controller-b5p69               1/1     Running   83         79d
ingress-nginx          nginx-ingress-controller-m6795               1/1     Running   73         79d
kube-system            coredns-7ff77c879f-7mhzg                     1/1     Running   1          33d
kube-system            coredns-7ff77c879f-pcvvz                     1/1     Running   1          33d
kube-system            etcd-k8s-master01                            1/1     Running   5          166d
kube-system            kube-apiserver-k8s-master01                  1/1     Running   5          166d
kube-system            kube-controller-manager-k8s-master01         1/1     Running   5          166d
kube-system            kube-flannel-ds-amd64-c2r48                  1/1     Running   1          33d
kube-system            kube-flannel-ds-amd64-pplwg                  1/1     Running   1          33d
kube-system            kube-flannel-ds-amd64-vgtv2                  1/1     Running   1          33d
kube-system            kube-proxy-6p7zj                             1/1     Running   8          166d
kube-system            kube-proxy-cdnfl                             1/1     Running   10         166d
kube-system            kube-proxy-wfblp                             1/1     Running   10         166d
kube-system            kube-scheduler-k8s-master01                  1/1     Running   5          166d
kubernetes-dashboard   dashboard-metrics-scraper-6b4884c9d5-b992s   1/1     Running   4          63d
kubernetes-dashboard   kubernetes-dashboard-7b544877d5-xj8wv        1/1     Running   4          63d

如上可以查看所有命名空间的pod了

2.5 ServiceAccount

Service Account也是一种账号,但它并不是给Kubernetes集群的用户(系统管理员、运维人员、租户用户等)用的,而是给运行在Pod里的进程用的,它为Pod里的进程提供了必要的身份证明。

2.5.1 创建一个只能访问某个 namespace 的ServiceAccount

创建一个集群内部的用户只能操作 kube-system 这个命名空间

a.创建一个 ServiceAccount 对象,
通过yaml文件方式创建
apiVersion: v1
kind: ServiceAccount
metadata:
  name: devops
  namespace: kube-system

或者 通过命令行方式
[root@k8s-master01 rbac]# kubectl create sa devops -n kube-system  -o yaml --dry-run 
apiVersion: v1
kind: ServiceAccount
metadata:
  creationTimestamp: null
  name: devops
  namespace: kube-system

kubectl create sa devops -n kube-system # sa=ServiceAccount

创建一个Role 对象
[root@k8s-master01 rbac]# kubectl apply -f devops-role.yaml
role.rbac.authorization.k8s.io/devops-sa-role created
[root@k8s-master01 rbac]# cat devops-role.yaml
apiVersion: rbac.authorization.k8s.io/v1
kind: Role
metadata:
  name: devops-sa-role
  namespace: kube-system
rules:
- apiGroups: [""]
  resources: ["pods"]
  verbs: ["get", "watch", "list"]
- apiGroups: ["apps"]
  resources: ["deployments"]
  verbs: ["get", "list", "watch", "create", "update", "patch", "delete"]
[root@k8s-master01 rbac]# 

创建一个 RoleBinding 对象
[root@k8s-master01 rbac]# kubectl apply -f devops-role-binding.yaml 
rolebinding.rbac.authorization.k8s.io/devops-sa-rolebinding created
[root@k8s-master01 rbac]# cat devops-role-binding.yaml
kind: RoleBinding
apiVersion: rbac.authorization.k8s.io/v1
metadata:
  name: devops-sa-rolebinding
  namespace: kube-system
subjects:
- kind: ServiceAccount
  name: devops
  namespace: kube-system
roleRef:
  kind: Role
  name: devops-sa-role
  apiGroup: rbac.authorization.k8s.io

验证devops serviceaccount权限,利用这个 token 去登录 Dashboard
[root@k8s-master01 rbac]# kubectl get secret -n kube-system |grep devops
devops-token-2xdgg                               kubernetes.io/service-account-token   3      9m7s
[root@k8s-master01 rbac]# kubectl get secret devops-token-2xdgg -o jsonpath={.data.token} -n kube-system |base64 -d
eyJhbGciOiJSUzI1NiIsImtpZCI6InNpSmpRLVlIRWphVE5YWHJ6SUhZS2RVbm94b0Y5VlI2ZEdic2txaDR4Y28ifQ.eyJpc3MiOiJrdWJlcm5ldGVzL3NlcnZpY2VhY2NvdW50Iiwia3ViZXJuZXRlcy5pby9zZXJ2aWNlYWNjb3VudC9uYW1lc3BhY2UiOiJrdWJlLXN5c3RlbSIsImt1YmVybmV0ZXMuaW8vc2VydmljZWFjY291bnQvc2VjcmV0Lm5hbWUiOiJkZXZvcHMtdG9rZW4tMnhkZ2ciLCJrdWJlcm5ldGVzLmlvL3NlcnZpY2VhY2NvdW50L3NlcnZpY2UtYWNjb3VudC5uYW1lIjoiZGV2b3BzIiwia3ViZXJuZXRlcy5pby9zZXJ2aWNlYWNjb3VudC9zZXJ2aWNlLWFjY291bnQudWlkIjoiYTdjMzg1MTQtMGUxNi00NjU2LWE5OTktOGI2NzJhODhlYjU3Iiwic3ViIjoic3lzdGVtOnNlcnZpY2VhY2NvdW50Omt1YmUtc3lzdGVtOmRldm9wcyJ9.WPhKZSxprCISJ-WPFZLc9TYcbLF3cThsErSaz0oWLXXcNV-SbDQq_SyxJmcd8-m6l0MDm-RO1RcNGRjHc4-ZGZIm0oZ7FDSdHDj3IfEIAEZ7KH7xMzrtgthWLMVIcM7NJkRC6GykQQqXdLpNCxau9v8NUGzHNUmpP75zdDh-aCuUvGll709K9qOQV9zXC8ufD29o6YyYiS8wzF7LFYc533rF4dQw9os0P2dpevTneveDp2ZAHDAZgUMdXqr684hBRHXANHFStrfeBMwp5gVe8f5kgqJqmRjW68lFZurYF9jfw8HqKw8WOhYHuFuvvTKks-wCb7H-O-6MW4D8LWkJvA[root@k8s-master01 rbac]# 

k8s基础入门之RBAC实战

我们可以看到上面的提示信息,这是因为我们登录进来后默认跳转到default命名空间,我们切换到 kube-system 命名空间下面就可以了:

k8s基础入门之RBAC实战

因为没有赋予查看service的权限 所以查看service没有权限
k8s基础入门之RBAC实战k8s基础入门之RBAC实战

2.5.2 创建一个可以访问所有namespace的ServiceAccount

创建ServiceAccount
[root@k8s-master01 rbac]#  kubectl create sa devopsall -n kube-system
serviceaccount/devopsall created

创建一个 ClusterRoleBinding 对象
[root@k8s-master01 rbac]# kubectl apply -f devopsall-role-ClusterRoleBinding.yaml
clusterrolebinding.rbac.authorization.k8s.io/devops-sa-ClusterRoleBinding created
[root@k8s-master01 rbac]# cat devopsall-role-ClusterRoleBinding.yaml
kind: ClusterRoleBinding
apiVersion: rbac.authorization.k8s.io/v1
metadata:
  name: devops-sa-ClusterRoleBinding
subjects:
- kind: ServiceAccount
  name: devopsall
  namespace: kube-system
roleRef:
  kind: ClusterRole
  name: cluster-admin
  apiGroup: rbac.authorization.k8s.io

我们没有为这个资源对象声明namespace,因为这是一个ClusterRoleBinding资源对象,是作用于整个集群的,我们也没有单独新建一个ClusterRole对象,而是使用的cluster-admin这个对象,这是Kubernetes集群内置ClusterRole 对象,我们可以使用kubectl get clusterrole 和kubectl get clusterrolebinding查看系统内置的一些集群角色和集群角色绑定,这里我们使用的cluster-admin这个集群角色是拥有最高权限的集群角色,所以一般需要谨慎使用该集群角色。

ServiceAccount 对应的 token 去登录 Dashboard 验证下
[root@k8s-master01 rbac]#  kubectl get secret -n kube-system |grep devopsall
devopsall-token-gx6rd                            kubernetes.io/service-account-token   3      9m14s
[root@k8s-master01 rbac]# kubectl get secret devopsall-token-gx6rd -o jsonpath={.data.token} -n kube-system |base64 -d
eyJhbGciOiJSUzI1NiIsImtpZCI6InNpSmpRLVlIRWphVE5YWHJ6SUhZS2RVbm94b0Y5VlI2ZEdic2txaDR4Y28ifQ.eyJpc3MiOiJrdWJlcm5ldGVzL3NlcnZpY2VhY2NvdW50Iiwia3ViZXJuZXRlcy5pby9zZXJ2aWNlYWNjb3VudC9uYW1lc3BhY2UiOiJrdWJlLXN5c3RlbSIsImt1YmVybmV0ZXMuaW8vc2VydmljZWFjY291bnQvc2VjcmV0Lm5hbWUiOiJkZXZvcHNhbGwtdG9rZW4tZ3g2cmQiLCJrdWJlcm5ldGVzLmlvL3NlcnZpY2VhY2NvdW50L3NlcnZpY2UtYWNjb3VudC5uYW1lIjoiZGV2b3BzYWxsIiwia3ViZXJuZXRlcy5pby9zZXJ2aWNlYWNjb3VudC9zZXJ2aWNlLWFjY291bnQudWlkIjoiMWJjMjA4OTYtNzAwMy00ZmRkLTg5ZWMtYWY5YWYwZDg4MGFiIiwic3ViIjoic3lzdGVtOnNlcnZpY2VhY2NvdW50Omt1YmUtc3lzdGVtOmRldm9wc2FsbCJ9.42l5Tdi_RrIjkJii9d4Lv1E68x1Hy6QdY2zILTvpnH0cb75XLedAiZX1gcHzuzlmiS7DjmeEo8UOicYCsCc7zWvD2Ag2RTBfURg5ngyNt5rjiBOQYGJ9ZCRyXR__xDzTQw1o15Lk6_JC1sl6DTKjKllOgQtQjOYL_iJhR3Nn2uiGqi-2kbHKT_Tnd-RkfhlYlHz86HmmAoQMEUlADt02yRIzefnpW9jc8N4-7ld8Oj6HeEgEE_xV-SDtE_rD2K_NYWoWQHrUnFoRquFU6OhekCFHy0ch-tenRNQqeQv8fL6eyOspAiy0H1tjjm0hIaS8wQ2_E6kvQZtfCMrqOBKbxA[root@k8s-master01 rbac]# 
访问浏览器如下
https://192.168.10.71:30001/#/login

k8s基础入门之RBAC实战

由于我们赋予的权限比较大,所以其他组也能访问,所有的命名空间都可以访问

k8s基础入门之RBAC实战

2.6 基于用户组的rbac

Subjects的kind类型除了User,ServiceAccount之外,还有一个Group,就是一组用户的意思。如果你为Kubernetes配置了外部认证服务的话,这个用户组就由外部认证服务提供。而对于Kubernetes内置用户ServiceAccount来说,其也有用户和用户组的概念,其中对于一个ServiceAccount,其在Kubernetes中对应的用户是:
system:serviceaccount:<ServiceAccount名字>
而对于其用户组是:
system:serviceaccounts:<Namespace名字>
比如我们定义下面这个RoleBinding:
subjects:
- kind: Group
  name: system:serviceaccounts:devops
  apiGroup: rbac.authorization.k8s.io

再比如:
subjects:
- kind: Group
  name: system:serviceaccounts
  apiGroup: rbac.authorization.k8s.io

kubernetes已经内置了许多ClusterRole,以system:开头,可以用kubectl get clusterrole查看。

3 常用的集群角色例子

Kubernetes还提供了四个预先定义好的ClusterRole来供用户直接使用,它们是:
• cluster-admin:超管
• admin:普通管理权限
• edit:修改权限
• view:只读权限

Dashboard 权限设置中,有两个主要集群角色: cluster-admin、view,一个是管理员权限,一个是查看权限。
创建能列出名称空间的集群角色
[root@hdss7-200 ~]# cat /data/k8s-yaml/dashboard/dashboard_1.10.1/list-namespace.yaml 

apiVersion: rbac.authorization.k8s.io/v1

kind: ClusterRole

metadata: 

  name: list-namespace

rules:

- apiGroups:

  - ""

  resources:

  - namespaces

  verbs:

  - list

  RBAC授权
[root@hdss7-200 ~]# cat /data/k8s-yaml/dashboard/dashboard_1.10.1/namespace-admin.yaml 
# 创建service account 账户
apiVersion: v1
kind: ServiceAccount
metadata:
  labels:
    k8s-app: kubernetes-dashboard
    addonmanager.kubernetes.io/mode: Reconcile
  name: ns-admin
  namespace: kube-system
---
授权default名称空间的管理员权限
apiVersion: rbac.authorization.k8s.io/v1
kind: RoleBinding
metadata:
  name: ns-admin-default
  namespace: default
  labels:
    k8s-app: kubernetes-dashboard
    addonmanager.kubernetes.io/mode: Reconcile
roleRef:
  apiGroup: rbac.authorization.k8s.io
  kind: ClusterRole
  name: cluster-admin
subjects:
- kind: ServiceAccount
  name: ns-admin
  namespace: kube-system
---
授予app名称空间的管理员权限
apiVersion: rbac.authorization.k8s.io/v1
kind: RoleBinding
metadata:
  name: ns-admin-app
  namespace: app
  labels:
    k8s-app: kubernetes-dashboard
    addonmanager.kubernetes.io/mode: Reconcile
roleRef:
  apiGroup: rbac.authorization.k8s.io
  kind: ClusterRole
  name: cluster-admin
subjects:
- kind: ServiceAccount
  name: ns-admin
  namespace: kube-system
---
可以查到到其它名称空间,方便切换。不受该权限时,需要手动修改URL中namespace完成切换
apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRoleBinding
metadata:
  name: ns-admin-list-namespace
  labels:
    k8s-app: kubernetes-dashboard
    addonmanager.kubernetes.io/mode: Reconcile
roleRef:
  apiGroup: rbac.authorization.k8s.io
  kind: ClusterRole
  name: list-namespace
subjects:
- kind: ServiceAccount
  name: ns-admin
  namespace: kube-system
单个名称空间浏览权限
[root@hdss7-200 ~]# cat /data/k8s-yaml/dashboard/dashboard_1.10.1/namespace-view.yaml
apiVersion: v1
kind: ServiceAccount
metadata:
  labels:
    k8s-app: kubernetes-dashboard
    addonmanager.kubernetes.io/mode: Reconcile
  name: ns-view
  namespace: kube-system
---
apiVersion: rbac.authorization.k8s.io/v1
kind: RoleBinding
metadata:
  name: ns-view-default
  namespace: default
  labels:
    k8s-app: kubernetes-dashboard
    addonmanager.kubernetes.io/mode: Reconcile
roleRef:
  apiGroup: rbac.authorization.k8s.io
  kind: ClusterRole
  name: view
subjects:
- kind: ServiceAccount
  name: ns-view
  namespace: kube-system

参考:https://www.yuque.com/duduniao/k8s/myrwhq#46boX
  • 我的微信
  • 这是我的微信扫一扫
  • weinxin
  • 我的微信公众号
  • 我的微信公众号扫一扫
  • weinxin
avatar

发表评论

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: