该脚本适用于管理员创建,脚本中证书按实际修改,有需要请自取。
#!/bin/bash
USERNAME="$1"
APISERVER="https://10.0.0.150:6443"
CA_FILE="/opt/kubernetes/ssl/ca.pem"
CA_KEY_FILE="/opt/kubernetes/ssl/ca-key.pem"
USERNAME_DIR="/opt/kubernetes/user/${USERNAME}"
if [ ! -d ${USERNAME_DIR} ];then
mkdir -p ${USERNAME_DIR}
fi
cd ${USERNAME_DIR}
if [ -z ${USERNAME} ];then
echo "用户名不能为空"
exit 1
fi
if [ ! -f ${CA_FILE} ];then
echo "${CA_FILE},ca证书不存在,请检查。"
exit 1
fi
if [ ! -f ${CA_KEY_FILE} ];then
echo "${CA_KEY_FILE},ca-key证书文件不存在,请检查。"
exit 1
fi
res=$(kubectl get clusterrolebinding | awk '{print $1}' | grep ^${USERNAME}$)
if [ ! -z ${res} ];then
echo "clusterrolebinding名称已存在"
exit 1
fi
# 生成用户的私钥文件
openssl genrsa -out ${USERNAME}.key 2048 # 利用用户的私钥,生成用户的公钥文件
openssl req -new -key ${USERNAME}.key -out ${USERNAME}.csr -subj "/CN=${USERNAME}/O=k8s"
openssl x509 -req -in ${USERNAME}.csr -CA ${CA_FILE} -CAkey ${CA_KEY_FILE} -CAcreateserial -out ${USERNAME}.crt -days 3650
kubectl config set-cluster ${USERNAME} --certificate-authority=${CA_FILE} --embed-certs=true --server=${APISERVER} --kubeconfig=${USERNAME}.conf
kubectl config set-credentials ${USERNAME} --client-certificate=${USERNAME}.crt --client-key=${USERNAME}.key --embed-certs=true --kubeconfig=${USERNAME}.conf
kubectl config set-context ${USERNAME}-context@${USERNAME} --cluster=${USERNAME} --user=${USERNAME} --kubeconfig=${USERNAME}.conf
kubectl config use-context ${USERNAME}-context@${USERNAME} --kubeconfig=${USERNAME}.conf
kubectl create clusterrolebinding ${USERNAME} --clusterrole=cluster-admin --user=${USERNAME}
示例 :
[root@k8s-master3 ~]# ./create_admin_user guilin
Generating RSA private key, 2048 bit long modulus
.................................................................................................................................+++
......................................................+++
e is 65537 (0x10001)
Signature ok
subject=/CN=guilin/O=k8s
Getting CA Private Key
Cluster "guilin" set.
User "guilin" set.
Context "guilin-context@guilin" created.
Switched to context "guilin-context@guilin".
clusterrolebinding.rbac.authorization.k8s.io/guilin created
生成后会在/opt/kubernetes/user/guilin