k8s 创建用户

创建用户:
用户名为 backend 所属组为 dev

创建新的 namespace work:

1
2
kubectl create namespace work
mkdir work && cd work

创建私钥:

1
openssl genrsa -out backend.key 2048

使用私钥生成证书请求:

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

使用 CA 进行签名。K8S 默认的证书目录为 /etc/kubernetes/pki:

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

查看生成的证书文件:

1
openssl x509 -in backend.crt -text -noout

添加 context:

1
2
kubectl config set-credentials backend --client-certificate=/root/work/backend.crt  --client-key=/root/work/backend.key
kubectl config set-context backend-context --cluster=kind --namespace=work --user=backend

使用新用户测试访问:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
kubectl --context=backend-context get pods
root@testkind:~/work# kubectl --context=backend-context get pods -n work -v 5
I0417 09:32:05.711722 20713 helpers.go:196] server response object: [{
"kind": "Status",
"apiVersion": "v1",
"metadata": {},
"status": "Failure",
"message": "pods is forbidden: User \"backend\" cannot list resource \"pods\" in API group \"\" in the namespace \"work\"",
"reason": "Forbidden",
"details": {
"kind": "pods"
},
"code": 403
}]
F0417 09:32:05.711843 20713 helpers.go:114] Error from server (Forbidden): pods is forbidden: User "backend" cannot list resource "pods" in API group "" in the namespace "work"

创建 Role 配置文件:

1
2
3
4
5
6
7
8
9
10
11
cat <<EOF > backend-role.yaml 
kind: Role
apiVersion: rbac.authorization.k8s.io/v1
metadata:
namespace: work
name: backend-role
rules:
- apiGroups: [""]
resources: ["pods"]
verbs: ["get", "list", "watch"]
EOF

创建 Role:

1
kubectl create -f backend-role.yaml

查看:

1
kubectl get roles  -n work -o yaml

创建Rolebinding 配置文件::

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
cat <<EOF > backend-rolebind.yaml
kind: RoleBinding
apiVersion: rbac.authorization.k8s.io/v1
metadata:
name: backend-rolebinding
namespace: work
subjects:
- kind: User
name: backend
apiGroup: ""
roleRef:
kind: Role
name: backend-role
apiGroup: ""
EOF

创建 Rolebinding:

1
kubectl create -f backend-rolebind.yaml

查看 Rolebinding:

1
kubectl get rolebinding -o yaml -n work

测试用户权限:

1
2
3
// 用户已经具备查看 Pod 的权限,但并不能查看 Namespace 或者 deployment 等其他资源
kubectl --context=backend-context get pods -n work
kubectl --context=backend-context get ns

调试权限:

1
2
3
// --as 是一种建立在 K8S 认证机制之上的机制,可以便于系统管理员验证授权情况,或进行调试。
kubectl auth can-i list pods -n work --as="backend"
kubectl auth can-i list deploy -n work --as="backend"

也可以仿照 ~/.kube/config 文件的内容,将当前生成的证书及私钥文件等写入到配置文件中,通过指定 KUBECONFIG 的环境变量,或者给 kubectl 传递 --kubeconfig 参数来使用

简化操作:

kubectx