原文:https://hbayraktar.medium.com/how-to-create-a-user-in-a-kubernetes-cluster-and-grant-access-bfeed991a0ef
1.使用openssl生成密钥对和CSR(Certificate Signing Request )
openssl genrsa -out developer.key 2048 openssl req -new -key developer.key -out developer.csr -subj "/CN=developer"
2.创建CSR YAML文件
cat <<EOF > csr_template.yaml apiVersion: certificates.k8s.io/v1 kind: CertificateSigningRequest metadata: name: developer-csr spec: request: <Base64_encoded_CSR> signerName: kubernetes.io/kube-apiserver-client usages: - client auth EOF
3.使用base64编码developer.csr文件中的内容,替换<Base64_encoded_CSR>
CSR_CONTENT=$(cat developer.csr | base64 | tr -d '\n') sed "s|<Base64_encoded_CSR>|$CSR_CONTENT|" csr_template.yaml > developer_csr.yaml
4.在kubernetes中创建csr
#创建 kubectl create -f developer_csr.yaml #查看 kubectl get csr #通过CSR kubectl certificate approve developer-csr #查看通过的CSR证书 kubectl get csr developer-csr -o jsonpath='{.status.certificate}'
5.导出通过的CSR证书
kubectl get csr developer-csr -o jsonpath='{.status.certificate}' | base64 --decode > developer.crt
6.生成新的kubeconfig文件
#查看当前集群配置信息 kubectl config view #根据当前集群信息创建新的kubeconfig文件 kubectl config set-cluster kubernetes --server=https://127.0.0.1:6443 --certificate-authority=/var/lib/rancher/k3s/server/tls/server-ca.crt --embed-certs=true --kubeconfig=developer.kubeconfig #设置用户认证信息 kubectl config set-credentials developer --client-certificate=developer.crt --client-key=developer.key --embed-certs=true --kubeconfig=developer.kubeconfig #设置用户上下文 kubectl config set-context developer-context --cluster=kubernetes --namespace=default --user=developer --kubeconfig=developer.kubeconfig #切换到用户上下文 kubectl config use-context developer-context --kubeconfig=developer.kubeconfig
7.添加用户对应的ClusterRole,设置访问权限
#创建ClusterRole cat <<EOF > developer-cluster-role.yaml apiVersion: rbac.authorization.k8s.io/v1 kind: ClusterRole metadata: name: developer-role rules: - apiGroups: ["", "extensions", "apps"] resources: ["*"] verbs: ["*"] EOF
#绑定用户和ClusterRole
cat <<EOF > developer-role-binding.yaml
apiVersion: rbac.authorization.k8s.io/v1
kind: RoleBinding
metadata:
name: developer-binding
namespace: default
subjects:
- kind: User
name: developer
apiGroup: rbac.authorization.k8s.io
roleRef:
kind: ClusterRole
name: developer-role
apiGroup: rbac.authorization.k8s.io
EOF
kubectl apply -f developer-cluster-role.yaml -f developer-role-binding.yaml
8.测试用户
kubectl --kubeconfig=developer.kubeconfig get pods kubectl --kubeconfig=developer.kubeconfig run nginx --image=nginx kubectl --kubeconfig=developer.kubeconfig get pods标签:kubectl,kubernetes,--,创建,用户,kubeconfig,yaml,csr,developer From: https://www.cnblogs.com/brightdays/p/18370342