在k8s的集群中对于资源对象的操作都是通过 APIServer 进行的,那么集群是怎样知道我们的请求就是合法的请求呢?这个就需要了解 Kubernetes 中另外一个非常重要的知识点了:RBAC(基于角色的权限控制)。

管理员可以通过 Kubernetes API 动态配置策略来启用RBAC,需要在 kube-apiserver 中添加参数--authorization-mode=RBAC

查看静态pod,kube-api的yaml文件,如下:

[root@master ~]# cat  /etc/kubernetes/manifests/kube-apiserver.yaml | grep -i rbac
    - --authorization-mode=Node,RBAC
[root@master ~]# 
[root@master ~]# 

API对象

在 Kubernetes 集群中,Kubernetes 对象是我们持久化的实体,就是最终存入 etcd 中的数据,集群中通过这些实体来表示整个集群的状态。

Kubernetes API 是一个以 JSON 为主要序列化方式的 HTTP 服务,除此之外也支持 Protocol Buffers 序列化方式,主要用于集群内部组件间的通信。为了可扩展性,Kubernetes 在不同的 API 路径(比如/api/v1 或者 /apis/batch)下面支持了多个 API 版本,不同的 API 版本意味着不同级别的稳定性和支持:

  • Alpha 级别,例如 v1alpha1 默认情况下是被禁用的,可以随时删除对功能的支持,所以要慎用

  • Beta 级别,例如 v2beta1 默认情况下是启用的,表示代码已经经过了很好的测试,但是对象的语义可能会在随后的版本中以不兼容的方式更改

  • 稳定级别,比如 v1 表示已经是稳定版本了,也会出现在后续的很多版本中。
    在 Kubernetes 集群中,一个 API 对象在 Etcd 里的完整资源路径,是由:Group(API 组)Version(API 版本)Resource(API 资源类型)三个部分组成的。

如下可以看到集群中的api形式:

[root@master ~]# kubectl get --raw /
{
  "paths": [
    "/.well-known/openid-configuration",
    "/api",
    "/api/v1",
    "/apis",
    "/apis/",
    "/apis/admissionregistration.k8s.io",
    "/apis/admissionregistration.k8s.io/v1",
    "/apis/apiextensions.k8s.io",
    "/apis/apiextensions.k8s.io/v1",
    "/apis/apiregistration.k8s.io",
    "/apis/apiregistration.k8s.io/v1",
    "/apis/apps",
    "/apis/apps/v1",
    "/apis/authentication.k8s.io",
    "/apis/authentication.k8s.io/v1",
    "/apis/authorization.k8s.io",
    "/apis/authorization.k8s.io/v1",
    "/apis/autoscaling",
    "/apis/autoscaling/v1",
    "/apis/autoscaling/v2",
    "/apis/autoscaling/v2beta2",
    "/apis/batch",
    "/apis/batch/v1",
    "/apis/certificates.k8s.io",
    "/apis/certificates.k8s.io/v1",
    "/apis/coordination.k8s.io",
    "/apis/coordination.k8s.io/v1",
    "/apis/crd.projectcalico.org",
    "/apis/crd.projectcalico.org/v1",
    "/apis/discovery.k8s.io",
    "/apis/discovery.k8s.io/v1",
    "/apis/events.k8s.io",
    "/apis/events.k8s.io/v1",
    "/apis/flowcontrol.apiserver.k8s.io",
    "/apis/flowcontrol.apiserver.k8s.io/v1beta1",
    "/apis/flowcontrol.apiserver.k8s.io/v1beta2",
    "/apis/metrics.k8s.io",
    "/apis/metrics.k8s.io/v1beta1",
    "/apis/networking.k8s.io",
    "/apis/networking.k8s.io/v1",
    "/apis/node.k8s.io",
    "/apis/node.k8s.io/v1",
    "/apis/policy",
    "/apis/policy/v1",
    "/apis/rbac.authorization.k8s.io",
    "/apis/rbac.authorization.k8s.io/v1",
    "/apis/scheduling.k8s.io",
    "/apis/scheduling.k8s.io/v1",
    "/apis/storage.k8s.io",
    "/apis/storage.k8s.io/v1",
    "/apis/storage.k8s.io/v1beta1",
    "/healthz",
    "/healthz/autoregister-completion",
    "/healthz/etcd",
    "/healthz/log",
    "/healthz/ping",
    "/healthz/poststarthook/aggregator-reload-proxy-client-cert",
    "/healthz/poststarthook/apiservice-openapi-controller",
    "/healthz/poststarthook/apiservice-openapiv3-controller",
    "/healthz/poststarthook/apiservice-registration-controller",
    "/healthz/poststarthook/apiservice-status-available-controller",
    "/healthz/poststarthook/bootstrap-controller",
    "/healthz/poststarthook/crd-informer-synced",
    "/healthz/poststarthook/generic-apiserver-start-informers",
    "/healthz/poststarthook/kube-apiserver-autoregistration",
    "/healthz/poststarthook/priority-and-fairness-config-consumer",
    "/healthz/poststarthook/priority-and-fairness-config-producer",
    "/healthz/poststarthook/priority-and-fairness-filter",
    "/healthz/poststarthook/rbac/bootstrap-roles",
    "/healthz/poststarthook/scheduling/bootstrap-system-priority-classes",
    "/healthz/poststarthook/start-apiextensions-controllers",
    "/healthz/poststarthook/start-apiextensions-informers",
    "/healthz/poststarthook/start-cluster-authentication-info-controller",
    "/healthz/poststarthook/start-kube-aggregator-informers",
    "/healthz/poststarthook/start-kube-apiserver-admission-initializer",
    "/healthz/poststarthook/storage-object-count-tracker-hook",
    "/livez",
    "/livez/autoregister-completion",
    "/livez/etcd",
    "/livez/log",
    "/livez/ping",
    "/livez/poststarthook/aggregator-reload-proxy-client-cert",
    "/livez/poststarthook/apiservice-openapi-controller",
    "/livez/poststarthook/apiservice-openapiv3-controller",
    "/livez/poststarthook/apiservice-registration-controller",
    "/livez/poststarthook/apiservice-status-available-controller",
    "/livez/poststarthook/bootstrap-controller",
    "/livez/poststarthook/crd-informer-synced",
    "/livez/poststarthook/generic-apiserver-start-informers",
    "/livez/poststarthook/kube-apiserver-autoregistration",
    "/livez/poststarthook/priority-and-fairness-config-consumer",
    "/livez/poststarthook/priority-and-fairness-config-producer",
    "/livez/poststarthook/priority-and-fairness-filter",
    "/livez/poststarthook/rbac/bootstrap-roles",
    "/livez/poststarthook/scheduling/bootstrap-system-priority-classes",
    "/livez/poststarthook/start-apiextensions-controllers",
    "/livez/poststarthook/start-apiextensions-informers",
    "/livez/poststarthook/start-cluster-authentication-info-controller",
    "/livez/poststarthook/start-kube-aggregator-informers",
    "/livez/poststarthook/start-kube-apiserver-admission-initializer",
    "/livez/poststarthook/storage-object-count-tracker-hook",
    "/logs",
    "/metrics",
    "/openapi/v2",
    "/openapi/v3",
    "/openapi/v3/",
    "/openid/v1/jwks",
    "/readyz",
    "/readyz/autoregister-completion",
    "/readyz/etcd",
    "/readyz/etcd-readiness",
    "/readyz/informer-sync",
    "/readyz/log",
    "/readyz/ping",
    "/readyz/poststarthook/aggregator-reload-proxy-client-cert",
    "/readyz/poststarthook/apiservice-openapi-controller",
    "/readyz/poststarthook/apiservice-openapiv3-controller",
    "/readyz/poststarthook/apiservice-registration-controller",
    "/readyz/poststarthook/apiservice-status-available-controller",
    "/readyz/poststarthook/bootstrap-controller",
    "/readyz/poststarthook/crd-informer-synced",
    "/readyz/poststarthook/generic-apiserver-start-informers",
    "/readyz/poststarthook/kube-apiserver-autoregistration",
    "/readyz/poststarthook/priority-and-fairness-config-consumer",
    "/readyz/poststarthook/priority-and-fairness-config-producer",
    "/readyz/poststarthook/priority-and-fairness-filter",
    "/readyz/poststarthook/rbac/bootstrap-roles",
    "/readyz/poststarthook/scheduling/bootstrap-system-priority-classes",
    "/readyz/poststarthook/start-apiextensions-controllers",
    "/readyz/poststarthook/start-apiextensions-informers",
    "/readyz/poststarthook/start-cluster-authentication-info-controller",
    "/readyz/poststarthook/start-kube-aggregator-informers",
    "/readyz/poststarthook/start-kube-apiserver-admission-initializer",
    "/readyz/poststarthook/storage-object-count-tracker-hook",
    "/readyz/shutdown",
    "/version"
  ]
}[root@master ~]# 

也可以通过 kubectl 来查询对应对象下面的数据:

[root@master ~]#  kubectl get --raw /api/v1 | python -m json.tool  |more
{
    "groupVersion": "v1",
    "kind": "APIResourceList",
    "resources": [
        {
            "kind": "Binding",
            "name": "bindings",
            "namespaced": true,
            "singularName": "",
            "verbs": [
                "create"
            ]
        },
        {
            "kind": "ComponentStatus",
            "name": "componentstatuses",
            "namespaced": false,
            "shortNames": [
                "cs"
            ],
            "singularName": "",
            "verbs": [
                "get",
                "list"
            ]
        },
        {
            "kind": "ConfigMap",
            "name": "configmaps",
            "namespaced": true,
            "shortNames": [
                "cm"
            ],
            "singularName": "",
            "storageVersionHash": "qFsyl6wFWjQ=",
            "verbs": [
                "create",
                "delete",
                "deletecollection",
                "get",
                "list",
                "patch",
                "update",
                "watch"
            ]
        },
        {
            "kind": "Endpoints",
            "name": "endpoints",
            "namespaced": true,
            "shortNames": [
                "ep"
            ],
            "singularName": "",
            "storageVersionHash": "fWeeMqaN/OA=",
            "verbs": [
                "create",
                "delete",
                "deletecollection",
                "get",
                "list",
                "patch",
                "update",
                "watch"
            ]
        },
        {
            "kind": "Event",
            "name": "events",
            "namespaced": true,
            "shortNames": [
                "ev"
            ],
            "singularName": "",
            "storageVersionHash": "r2yiGXH7wu8=",
            "verbs": [
                "create",
                "delete",
                "deletecollection",
                "get",
                "list",
                "patch",
                "update",
                "watch"
            ]
        },
        {
            "kind": "LimitRange",
            "name": "limitranges",
            "namespaced": true,
            "shortNames": [
                "limits"
            ],
            "singularName": "",
            "storageVersionHash": "EBKMFVe6cwo=",
            "verbs": [
                "create",
                "delete",
                "deletecollection",
                "get",
                "list",
                "patch",
                "update",
                "watch"
            ]
        },
        {
            "kind": "Namespace",
            "name": "namespaces",
            "namespaced": false,
            "shortNames": [
                "ns"
            ],
            "singularName": "",
            "storageVersionHash": "Q3oi5N2YM8M=",
            "verbs": [
                "create",
                "delete",
                "get",
                "list",
                "patch",
                "update",
                "watch"
            ]
.......................
.......................

通常,Kubernetes API 支持通过标准 HTTP POSTPUTDELETEGET 在指定 PATH 路径上创建、更新、删除和检索操作,并使用 JSON 作为默认的数据交互格式。

比如下面创建一个pod

apiVersion: apps/v1
kind: deployment

其中 Deployment 就是这个 API 对象的资源类型(Resource),apps 就是它的组(Group)v1 就是它的版本(Version)。API Group、Version 和 资源就唯一定义了一个 HTTP 路径,然后在 kube-apiserver 端对这个 url 进行了监听,然后把对应的请求传递给了对应的控制器进行处理。

RBAC

上面我们介绍了 Kubernetes 所有资源对象都是模型化的 API 对象,允许执行 CRUD(Create、Read、Update、Delete) 操作,比如下面的这些资源类型:

pods
deployment
service
deamonset
secret
configmap
........

对于上述之源可以进行如下操作:

create
get 
list
delete
update
watch
patch
edit
..........

在往上层,这些资源和 API Group 进行关联,比如 Pods 属于 Core API Group,而 Deployements 属于 apps API Group,现在我们要在 Kubernetes 中通过 RBAC 来对资源进行权限管理,除了上面的这些资源和操作以外,我们还需要了解另外几个概念:

  • Rule:规则,规则是一组属于不同 API Group 资源上的一组操作的集合

  • RoleClusterRole:角色和集群角色,这两个对象都包含上面的 Rules 元素,二者的区别在于,在 Role 中,定义的规则只适用于单个命名空间,而 ClusterRole 是集群范围内的,定义的规则不受命名空间的约束。

  • Subject:主题,对应集群中尝试操作的对象,集群中定义了3种类型的主题资源:

    • User Account:用户,这是有外部独立服务进行管理的,管理员进行私钥的分配,用户可以使用 KeyStone 或者 Goolge 帐号,甚至一个用户名和密码的文件列表也可以。对于用户的管理集群内部没有一个关联的资源对象,所以用户不能通过集群内部的 API 来进行管理
    • Group:组,这是用来关联多个账户的,集群中有一些默认创建的组,比如 cluster-admin
    • Service Account:服务帐号,通过 Kubernetes API 来管理的一些用户帐号,和 namespace 进行关联的,适用于集群内部运行的应用程序,需要通过 API 来完成权限认证,所以在集群内部进行权限操作,我们都需要使用到 ServiceAccount
  • RoleBindingClusterRoleBinding:角色绑定和集群角色绑定,简单来说就是把声明的 Subject 和我们的 Role 进行绑定的过程(给某个用户绑定上操作的权限),二者的区别也是作用范围的区别:RoleBinding 只会影响到当前 namespace 下面的资源操作权限,而 ClusterRoleBinding 会影响到所有的 namespace。

示例测试

  • 创建访问单个ns的serviceaccount账户
1:创建sa,编辑yaml文件如下:
apiVersion: v1
kind: ServiceAccount
metadata:
  name: sa-test
  namespace: kube-system


[root@master rbac]# kubectl apply -f  sa.yaml
serviceaccount/sa-test created
[root@master rbac]# 
[root@master rbac]# kubectl get sa -n kube-system  | grep sa-test
sa-test                              0         18s
[root@master rbac]# 

2:创建role,编辑yaml文件如下:
apiVersion: rbac.authorization.k8s.io/v1
kind: Role
metadata:
  name: sa-test-role
  namespace: kube-system
rules:
- apiGroups: [""]
  resources: ["pods"]
  verbs: ["get", "watch", "list"]   ####可以查看pod权限
- apiGroups: ["apps"]
  resources: ["deployments"]
  verbs: ["get", "list", "watch", "create", "update", "patch", "delete"]  ##可以创建删除更新deployment等操作
  
[root@master rbac]# kubectl apply -f  role.yaml 
role.rbac.authorization.k8s.io/sa-test-role created
[root@master rbac]# 
[root@master rbac]# kubectl get role -n kube-system  | grep sa-test-role 
sa-test-role                                     2023-04-03T14:29:56Z
[root@master rbac]#

3:创建rolebind,编辑yaml文件如下
kind: RoleBinding
apiVersion: rbac.authorization.k8s.io/v1
metadata:
  name: sa-test-rolebinding 
  namespace: kube-system
subjects:
- kind: ServiceAccount     ###绑定创建的serviceaccount账户
  name: sa-test
  namespace: kube-system
roleRef:
  kind: Role
  name: sa-test-role         ####选择使用的role
  apiGroup: rbac.authorization.k8s.io
  
[root@master rbac]# kubectl get RoleBinding -n kube-system  | grep sa-test
sa-test-rolebinding                                 Role/sa-test-role                                     23s
[root@master rbac]# 


4:创建secret,编辑yaml文件如下
apiVersion: v1
kind: Secret
metadata:
  name: secret-sa-sample
  namespace: kube-system
  annotations:
    kubernetes.io/service-account.name: "sa-test"   # 这里填写serviceAccountName
type: kubernetes.io/service-account-token

[root@master rbac]# kubectl apply -f  secret.yaml 
secret/secret-sa-test created
[root@master rbac]# kubectl get secret -nkube-system  |grep sa-test
secret-sa-test     kubernetes.io/service-account-token   3      16s
[root@master rbac]# 
#############################
注意:我使用的集群版本是 1.25.3,创建 serviceAccount 的时候发现没有生成 secret,查了一下发现从 1.24 开始就不会自动生成 secret 了。

5:获取上面创建secret token
[root@master rbac]# kubectl get secret secret-sa-test -o jsonpath={.data.token} -n kube-system |base64 -d
eyJhbGciOiJSUzI1NiIsImtpZCI6IjNBc3p2U3pSQnpLbF9jYkpYLVd4ZkR1THdMTkxGLXd4WHFDSk9ONXphWEUifQ.eyJpc3MiOiJrdWJlcm5ldGVzL3NlcnZpY2VhY2NvdW50Iiwia3ViZXJuZXRlcy5pby9zZXJ2aWNlYWNjb3VudC9uYW1lc3BhY2UiOiJrdWJlLXN5c3RlbSIsImt1YmVybmV0ZXMuaW8vc2VydmljZWFjY291bnQvc2VjcmV0Lm5hbWUiOiJzZWNyZXQtc2EtdGVzdCIsImt1YmVybmV0ZXMuaW8vc2VydmljZWFjY291bnQvc2VydmljZS1hY2NvdW50Lm5hbWUiOiJzYS10ZXN0Iiwia3ViZXJuZXRlcy5pby9zZXJ2aWNlYWNjb3VudC9zZXJ2aWNlLWFjY291bnQudWlkIjoiOWQ4OWQxZmUtN2FlYy00MTUxLWE2MzctZDE0YWMzODNkY2VjIiwic3ViIjoic3lzdGVtOnNlcnZpY2VhY2NvdW50Omt1YmUtc3lzdGVtOnNhLXRlc3QifQ.Ei9PdoecOuSN1Y7po7Q5ZW31OqqyLm_hRcaWtI8QK1Caf1wry_D_1ETe5tDKOnjR4Vx56jP_Fl2gNDDrj9PUb1CL_nxbKMfZLPs3chqwX6q2mYx7rJHm51K0bQcmI8iv5wRVijxZ9KmCwcRhja7mSb8yx4sfv2o4RYseQGeVE1qoEg_9FwW9dpZ9HfZPNGTYi59ABhAqNoQtVN6UQOWSeo_QHFnzGe7TPAnhtWJhFhZ_NeEGHm8jO7yAMODxLeyHnWcmAaBi0XOI0Adkh_pIrAOnQbW5dbuzO8f8KRo_lmKeeIu2nkFLK7AiDyeYpWEDSUf-0fqUNcNkyt4Jwl13-w[root@master rbac]# 
[root@master rbac]# 
[root@master rbac]#

使用获取的token登录dashboard,如下:
在这里插入图片描述
可以查看kube-system ns下的pod以及deployment
在这里插入图片描述
在这里插入图片描述
查看其它的资源类型没有返回结果
在这里插入图片描述
查看其它的ns下的资源无法查看
在这里插入图片描述

  • 创建访问整个集群的serviceaccount账户
1: 创建sa账户,如下:
[root@master rbac]# kubectl create sa sa-admin -n kube-system 
serviceaccount/sa-admin created

2:创建clusterrole,如下:
[root@master rbac]# cat clusterrole.yaml 
apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRole 
metadata:
  name: sa-clusterrole
  namespace: kube-system
rules:
- apiGroups: ["*"]
  resources: ["*"]
  verbs: ["*"]
  
[root@master rbac]# 
[root@master rbac]# kubectl apply -f  clusterrole.yaml 
clusterrole.rbac.authorization.k8s.io/sa-clusterrole created
[root@master rbac]# 
[root@master rbac]# 


3: 创建clusterrolebind,如下:
[root@master rbac]# cat cluserrolebind.yaml 
kind: ClusterRoleBinding
apiVersion: rbac.authorization.k8s.io/v1
metadata:
  name: sa-clusterrolebinding
  namespace: kube-system
subjects:
- kind: ServiceAccount
  name: sa-admin
  namespace: kube-system
roleRef:
  kind: ClusterRole
  name: sa-clusterrole
  apiGroup: rbac.authorization.k8s.io

4:创建secret,如下;
[root@master rbac]# cat secret.yaml 
apiVersion: v1
kind: Secret
metadata:
  name: secret-sa
  namespace: kube-system
  annotations:
    kubernetes.io/service-account.name: "sa-admin"   # 这里填写serviceAccountName
type: kubernetes.io/service-account-token
[root@master rbac]# 
[root@master rbac]# kubectl apply -f  secret.yaml 
secret/secret-sa created
[root@master rbac]# 

5:获取secret的token,如下:
[root@master rbac]# kubectl get secret secret-sa -o jsonpath={.data.token} -n kube-system |base64 -d
eyJhbGciOiJSUzI1NiIsImtpZCI6IjNBc3p2U3pSQnpLbF9jYkpYLVd4ZkR1THdMTkxGLXd4WHFDSk9ONXphWEUifQ.eyJpc3MiOiJrdWJlcm5ldGVzL3NlcnZpY2VhY2NvdW50Iiwia3ViZXJuZXRlcy5pby9zZXJ2aWNlYWNjb3VudC9uYW1lc3BhY2UiOiJrdWJlLXN5c3RlbSIsImt1YmVybmV0ZXMuaW8vc2VydmljZWFjY291bnQvc2VjcmV0Lm5hbWUiOiJzZWNyZXQtc2EiLCJrdWJlcm5ldGVzLmlvL3NlcnZpY2VhY2NvdW50L3NlcnZpY2UtYWNjb3VudC5uYW1lIjoic2EtYWRtaW4iLCJrdWJlcm5ldGVzLmlvL3NlcnZpY2VhY2NvdW50L3NlcnZpY2UtYWNjb3VudC51aWQiOiIzOGY4ZGZmYS1iZTQ3LTQxYzktOWM5Ni1kZGE3MDI4ODUzMTMiLCJzdWIiOiJzeXN0ZW06c2VydmljZWFjY291bnQ6a3ViZS1zeXN0ZW06c2EtYWRtaW4ifQ.Tzjf_v_RN59OHcRcAl6PASWUitXdVjeBRCLplZXsTbS9P56V353Tqgs3YNfRJjcEyvL9XhBwxTiKUNk9keaP-jPg32tr0iosub4w88Uvn1TUJSmUXXV1R3PbOQQslEc5l2-mShcWUYTWH9yJXP4e2DEcItyq_gIJYqzJSbFNeG96GAl8dK52-EXPgou1YebS4EmExVL2Q1AV4nazM7LgeLC0WGwwHuNxUePmBE4Goa4xOQb8eNslhqVVaJQE9wpFRni5sOr5aqJU4vQ6EhEJ6JSqfa37VZzeXDJ1n9xH2Vlwe1khTRW77yG5xtSv6mI12nLg7FiGV2XiH0X3CvLw3w[root@master rbac]# 
[root@master rbac]# 

登录k8s的dashboard界面如下:
在这里插入图片描述
可以查看其它ns下的资源,如下:
在这里插入图片描述
在这里插入图片描述

  • 创建访问单个ns的user account
1:创建一个系统用户weizb
[root@master ~]# useradd weizb

2:使用openssl工具为用户生成私钥weizb.key
[root@master key]# openssl genrsa -out weizb.key 2048
Generating RSA private key, 2048 bit long modulus
.....................................................+++
...+++
e is 65537 (0x10001)
[root@master key]# 

3:使用上面生成的私钥,为用户生成证书请求文件weizb.csr(注意-subj后面的CN表示用户,O表示组)
[root@master key]# openssl req -new -key weizb.key -out weizb.csr -subj "/CN=weizb/O=weizb"
[root@master key]# ll
total 8
-rw-r--r-- 1 root root  907 Apr  5 19:38 weizb.csr
-rw-r--r-- 1 root root 1675 Apr  5 19:35 weizb.key
[root@master key]# 

4:使用k8s集群的CA证书,来批准证书请求,最终生成wezb.cert证书文件,有效期为500天,k8s集群证书默认在/etc/kubernetes/pki/目录下
[root@master key]# openssl x509 -req -in weizb.csr -CA /etc/kubernetes/pki/ca.crt -CAkey /etc/kubernetes/pki/ca.key -CAcreateserial -out weizb.crt -days 500
Signature ok
subject=/CN=weizb/O=weizb
Getting CA Private Key
[root@master key]# 

5:查看证书内容
[root@master key]# ll
total 12
-rw-r--r-- 1 root root  993 Apr  5 19:41 weizb.crt
-rw-r--r-- 1 root root  907 Apr  5 19:38 weizb.csr
-rw-r--r-- 1 root root 1675 Apr  5 19:35 weizb.key

[root@master key]# openssl x509 -in weizb.crt  -noout -text
Certificate:
    Data:
        Version: 1 (0x0)
        Serial Number:
            a5:2b:a2:04:18:28:79:8c
    Signature Algorithm: sha256WithRSAEncryption
        Issuer: CN=kubernetes   ###证书的颁发机构
        Validity
            Not Before: Apr  5 11:41:44 2023 GMT
            Not After : Aug 17 11:41:44 2024 GMT  ###证书有效期
        Subject: CN=weizb, O=weizb
        Subject Public Key Info:
            Public Key Algorithm: rsaEncryption
                Public-Key: (2048 bit)
                Modulus:
                    00:c5:4d:dc:b6:3b:3e:03:3b:c3:79:bc:5c:a8:31:
                    c6:7c:4c:89:6e:29:a7:60:e4:02:68:f4:4c:2f:d9:
                    d0:c3:96:9d:20:fb:7a:14:83:d7:86:0b:bd:c0:40:
                    2a:7d:4a:ab:06:75:2b:55:6d:c8:c5:fd:41:aa:ee:
                    0c:a3:1d:b9:44:fa:1a:d7:de:27:a2:c0:ff:7e:e4:
                    77:a0:ec:08:00:87:a0:8a:e6:9b:a6:9a:b7:cc:10:
                    17:10:35:05:52:0b:26:78:77:b4:75:11:0c:c2:2d:
                    e8:1b:08:8c:05:6e:74:a6:8f:16:4d:49:88:3d:1c:
                    1e:13:01:16:86:80:f4:2a:44:0c:89:52:bd:d6:d7:
                    86:3c:a1:a7:fc:f0:13:7a:18:45:85:0f:09:f0:87:
                    27:a9:5c:33:d2:22:a8:d1:c9:fd:36:21:9d:01:62:
                    b9:58:df:bc:25:95:b9:45:9d:17:94:d1:89:4e:29:
                    98:24:f5:14:f9:aa:9c:d0:71:71:93:14:bd:ef:17:
                    b1:05:8a:d9:be:a7:63:5d:88:f1:63:1e:e3:ec:18:
                    75:2a:80:e9:8e:18:23:ee:45:9b:89:65:38:82:38:
                    97:60:af:2d:e1:9d:38:ea:8e:f7:c0:f9:8f:47:f1:
                    78:96:d3:96:f4:9c:68:a6:d5:e5:1f:58:cc:18:c9:
                    da:85
                Exponent: 65537 (0x10001)
    Signature Algorithm: sha256WithRSAEncryption
         c0:b0:0e:b3:a7:59:3d:73:94:07:bb:db:6d:b3:00:38:68:a5:
         06:93:e4:ee:11:5d:b6:3b:f3:9a:c9:12:fe:38:bc:5a:6b:2a:
         1a:a3:04:8c:e0:40:51:d7:20:26:a1:48:6c:7f:39:49:3e:b7:
         cd:9a:55:99:b7:e0:4e:af:3e:80:36:c7:7b:ce:de:7a:1a:89:
         d3:da:ed:cd:2d:06:4f:92:6a:68:88:f8:87:d5:0e:16:2b:84:
         02:b2:40:a3:d1:b8:62:bc:a2:91:7f:e7:bf:8a:d7:ea:c7:b4:
         65:8d:83:58:ea:c8:39:25:e2:98:fb:27:a7:af:12:d4:a5:ff:
         99:f5:36:11:52:29:66:73:c4:ab:df:b9:66:5e:da:0e:23:6f:
         ca:3c:d9:d6:aa:d0:ec:cb:3f:84:24:94:8a:11:85:31:27:5c:
         8d:51:7d:41:61:d0:fd:32:8c:1b:41:f8:cb:3a:7f:d5:62:39:
         aa:6f:fd:33:02:0c:5d:82:77:a7:98:4d:f5:f6:c9:ea:7e:e0:
         8e:0f:67:cc:81:49:7d:27:3a:9d:61:30:a2:ff:5d:87:ae:83:
         3e:c5:a3:2a:d4:91:ba:79:18:4c:22:6d:6f:cd:5e:85:e9:3b:
         f6:8c:de:a9:e3:e1:40:71:2e:75:65:e8:a3:66:15:b2:45:09:
         c9:a7:9b:f9
[root@master key]# 


6:使用创建的证书以及私钥配置新的凭证
[root@master key]# kubectl config set-credentials weizb --client-certificate=weizb.crt --client-key=weizb.key
User "weizb" set.
[root@master key]# 

7:为用户设置上下文context,指定某一个ns
   首先确认下自己的cluster名称,如下:
[root@master key]# kubectl config get-clusters 
NAME
test.com     ###我的是test.com

[root@master key]# kubectl config set-context weizb --cluster=test.com --user=weizb --namespace=kube-system 
Context "weizb" created.
[root@master key]# 
[root@master key]#

8: 使用contex查看下是否有权限
[root@master key]# 
[root@master key]# kubectl get po --context=weizb
Error from server (Forbidden): pods is forbidden: User "weizb" cannot list resource "pods" in API group "" in the namespace "kube-system"
[root@master key]# 

9:为用户创建role
apiVersion: rbac.authorization.k8s.io/v1
kind: Role
metadata:
  name: weizb-role
  namespace: kube-system
rules:
- apiGroups: [""]
  resources: ["pods"]
  verbs: ["get", "watch", "list"]
- apiGroups: ["apps"]
  resources: ["deployments"]
  verbs: ["get", "list", "watch", "create", "update", "patch", "delete"]


10:创建rolebinding,如下:
kind: RoleBinding
apiVersion: rbac.authorization.k8s.io/v1
metadata:
  name: weizb-rolebinding
  namespace: kube-system
subjects:
- kind: User
  name: weizb
  namespace: kube-system
roleRef:
  kind: Role
  name: weizb-role
  apiGroup: rbac.authorization.k8s.io
  
11:再次查看pod,deploy资源
[root@master key]# kubectl get deploy,pod,rs,rc  --context=weizb
NAME                                      READY   UP-TO-DATE   AVAILABLE   AGE
deployment.apps/calico-kube-controllers   1/1     1            1           122d
deployment.apps/coredns                   2/2     2            2           122d
deployment.apps/metrics-server            1/1     1            1           122d

NAME                                         READY   STATUS    RESTARTS        AGE
pod/calico-kube-controllers-57bcc88b-vb2q2   1/1     Running   16 (5d3h ago)   13d
pod/calico-node-4dt5p                        1/1     Running   1 (87d ago)     122d
pod/calico-node-kgmr2                        1/1     Running   1 (87d ago)     122d
pod/calico-node-pdh8x                        1/1     Running   7 (14d ago)     122d
pod/coredns-6d69f479b-2dc2f                  1/1     Running   1 (87d ago)     122d
pod/coredns-6d69f479b-m8qbn                  1/1     Running   1 (87d ago)     122d
pod/kube-apiserver-master                    1/1     Running   0               122d
pod/kube-controller-manager-master           1/1     Running   7 (2d3h ago)    122d
pod/kube-multus-ds-pjglm                     1/1     Running   0               27h
pod/kube-multus-ds-stbgf                     1/1     Running   0               27h
pod/kube-multus-ds-zxbwd                     1/1     Running   0               27h
pod/kube-proxy-ccsdp                         1/1     Running   1 (87d ago)     122d
pod/kube-proxy-tvzbc                         1/1     Running   7 (14d ago)     122d
pod/kube-proxy-x5fx5                         1/1     Running   1 (87d ago)     122d
pod/kube-scheduler-master                    1/1     Running   8 (2d3h ago)    122d
pod/metrics-server-68c648fbc7-w59hd          1/1     Running   0               20d
pod/nodelocaldns-7p9jb                       1/1     Running   1 (87d ago)     122d
pod/nodelocaldns-qzn8f                       1/1     Running   7 (14d ago)     122d
pod/nodelocaldns-tnwt6                       1/1     Running   1 (87d ago)     122d
pod/whereabouts-85tlt                        1/1     Running   0               28h
pod/whereabouts-msbf6                        1/1     Running   0               28h
pod/whereabouts-nzh89                        1/1     Running   0               28h

Logo

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

更多推荐