k8s基于clusterrole生成集群级别只读用户bash脚本

  • 2025-04-02 15:05:50
  • 脚本
  • 30
  • shevechco

在k8s集群中需要生成一些普通只读账户给平台人员使用,所以这里写了个一键脚本生成只读用户,是基于clusterrole创建的集群级别的用户,权限可以自己根据自己的需求进行修改,脚本内容如下:

#!/bin/bash

USER="suyang"
CLUSTER_IP="192.168.1.72"
CLUSTER_PORT="6443"
CA_PATH="/etc/kubernetes/pki"

if ! command -v "openssl" >/dev/null 2>&1; then
	echo "未安装openssl命令工具!"
	exit 1
fi 

echo "开始生成TLS证书..."
openssl genrsa -out ${USER}.key 2048
openssl req -new -key ${USER}.key -out ${USER}.csr -subj "/CN=${USER}"

echo "创建CSR证书文件"
openssl x509 -req -in ${USER}.csr -CA ${CA_PATH}/ca.crt -CAkey ${CA_PATH}/ca.key -CAcreateserial -out ${USER}.crt -days 365

echo "开始创建clusterrolebinding"
if ! command -v "kubectl" >/dev/null 2>&1; then
	echo "kubectl命令未找到!"
	exit 1
fi
kubectl create clusterrolebinding ${USER} --clusterrole=view --user=${USER}

CLUSTER_NAME=`kubectl config view | grep "cluster:" | tail -1 | awk -F ': ' '{print $2}'`

echo "获取证书base64..."
CER_DATA=`cat ${USER}.crt | base64 --wrap=0`
KEY_DATA=`cat ${USER}.key | base64 --wrap=0`
CA_DATA=`cat ${CA_PATH}/ca.crt | base64 --wrap=0`

echo "开始生成config管理配置文件..."
cat > ./${USER}_config <<EOF
apiVersion: v1
clusters:
- cluster:
    certificate-authority-data: ${CA_DATA}
    server: https://${CLUSTER_IP}:${CLUSTER_PORT}
  name: ${CLUSTER_NAME}
contexts:
- context:
    cluster: ${CLUSTER_NAME}
    user: ${USER}
  name: ${USER}@${CLUSTER_NAME}
current-context: ${USER}@${CLUSTER_NAME}
kind: Config
preferences: {}
users:
- name: ${USER}
  user:
    client-certificate-data: ${CER_DATA}
    client-key-data: ${KEY_DATA}
EOF

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:http://www.sulao.cn/post/1014

相关推荐