1.概述
访问k8s集群时候,需要经过三个步骤完成具体操作
第一步:认证
第二步:鉴权(授权)
第三步:准入控制
第一步 认证 传输安全
传输安全:对外不暴露8080端口,只能内部访问,对外使用端口6443
客户端身份证常用认证方式:
https证书认证,基于ca证书
http token认证,通过token识别用户
http基本认证,用户名+密码认证
第二步 鉴权(授权)
基于RBAC进行鉴权操作
基于角色访问控制
第三步 准入控制
就是准入控制器的列表,如果列表有请求内容,通过,不拒绝
2.RBAC 基于角色的访问控制
就是先设置一个角色role,然后给这个role授权,在把这个有操作权限的role和需要权限的主体绑定,这样这个主体也就有这个角色的权限了
角色
role:特定命名空间访问权限
ClusterRole:所有命名空间访问权限
角色绑定
roleBinding: 角色绑定到主体
ClusterRoleBinding: 集群角色绑定到主体
主体
user: 用户
group: 用户组
serviceAccount: 服务账号
3.RBAC实践
创建命名空间
kubectl create ns roledemo
在新创建的命名空间中创建pod
kubectl run nginx —image=nginx -n roledemo
创建角色
# vi rbac-role.yaml
kind: RoleapiVersion: rbac.authorization.k8s.io/v1metadata:namespace: ctnrsname: pod-readerrules:- apiGroups: [""] # "" indicates the core API groupresources: ["pods"]verbs: ["get", "watch", "list"]
kubectl apply -f rbac-role.yaml
kubectl get role -n roledemo
绑定角色
# vi rbac-rolebinding.yaml
kind: RoleBindingapiVersion: rbac.authorization.k8s.io/v1metadata:name: read-podsnamespace: roletestsubjects:- kind: Username: lucy # Name is case sensitiveapiGroup: rbac.authorization.k8s.ioroleRef:kind: Role #this must be Role or ClusterRolename: pod-reader # this must match the name of the Role or ClusterRole you wish to bind toapiGroup: rbac.authorization.k8s.io
kubectl apply -f rbac.rolebinding.yaml
kubectl get role,rolebinding -n roledemo
使用证书识别身份
# vi rbac-user.sh
cat > mary-csr.json <<EOF{"CN": "mary","hosts": [],"key": {"algo": "rsa","size": 2048},"names": [{"C": "CN","L": "BeiJing","ST": "BeiJing"}]}EOFcfssl gencert -ca=ca.pem -ca-key=ca-key.pem -config=ca-config.json -profile=kubernetes mary-csr.json | cfssljson -bare marykubectl config set-cluster kubernetes \--certificate-authority=ca.pem \--embed-certs=true \--server=https://192.168.10.20:6443 \--kubeconfig=mary-kubeconfigkubectl config set-credentials mary \--client-key=mary-key.pem \--client-certificate=mary.pem \--embed-certs=true \--kubeconfig=mary-kubeconfigkubectl config set-context default \--cluster=kubernetes \--user=mary \--kubeconfig=mary-kubeconfigkubectl config use-context default --kubeconfig=mary-kubeconfig
在二进制安装的集群上进行测试,把之前安装集群时候生成的ca证书拷贝过来
bash rbac-user.sh
kubectl get pods -n roledemo
