0%

k8s权限管理

k8s生成一个用户集群配置文件并限制用户的行为(让linux用户只能对某一个namespace特定的资源操作并且只具有查看权限,在实际工作中可以限定不同用户具有k8s不同的操作行为)

操作前提是已经有namespace,本文的namespace是fronted

新建用户

创建用户证书key

1
umask 077; openssl genrsa -out fronted.key 2048

创建用户证书请求,-subj指定组和用户,其中O是组名,CN是用户名

1
openssl req -new -key fronted.key -out fronted.csr -subj "/O=fronted/CN=fronted" 

使用k8s的ca签发用户证书

1
openssl x509 -req -in fronted.csr -CA /etc/kubernetes/pki/ca.crt -CAkey /etc/kubernetes/pki/ca.key -CAcreateserial -out fronted.crt -days 3650

生成kubeconfig授权文件

设置集群配置

1
kubectl config set-cluster fronted@kubernetes --certificate-authority=/etc/kubernetes/pki/ca.crt --embed-certs=true --server=https://master.k8s.io:16443 --kubeconfig=fronted.kubeconfig

设置context

1
kubectl config set-context fronted@kubernetes --cluster=kubernetes --user=fronted --kubeconfig=fronted.kubeconfig

设置客户端认证配置

1
kubectl config set-credentials fronted --client-certificate=fronted.crt --client-key=fronted.key --embed-certs=true --kubeconfig=fronted.kubeconfig

设置当前用户配置

1
kubectl config use-context fronted@kubernetes --kubeconfig=fronted.kubeconfig

创建RBAC授权

创建Role(只允许用户对namespace=fronted的pod进行查看操作包括日志查看) fronted-role.yaml

1
2
3
4
5
6
7
8
9
kind: Role
apiVersion: rbac.authorization.k8s.io/v1
metadata:
namespace: fronted
name: pod-reader
rules:
- apiGroups: [""]
resources: ["pods","pods/log"]
verbs: ["get", "watch", "list"]

创建RoleBinding(将用户fronted和Role进行绑定) fronted-rolebinding.yaml

1
2
3
4
5
6
7
8
9
10
11
12
13
kind: RoleBinding
apiVersion: rbac.authorization.k8s.io/v1
metadata:
name: read-pods
namespace: fronted
subjects:
- kind: User
name: fronted
apiGroup: rbac.authorization.k8s.io
roleRef:
kind: Role
name: pod-reader
apiGroup: rbac.authorization.k8s.io

应用RBAC

1
2
kubectl apply -f fronted-role.yaml
kubectl apply -f fronted-rolebinding.yaml

将k8s权限应用于linux普通用户

1
2
3
4
useradd fronted
mkdir -p /home/fronted/.kube
cp fronted.kubeconfig /home/fronted/.kube/
chown fronted.fronted /home/fronted/ -R