k8s创建只有更新deployments statefulsets权限用户

运维小白 8 阅读 linux
#!/bin/bash

# 脚本名称: k8s_create_update_user.sh
# 脚本功能: 创建k8s只具有更新deployments statefulsets权限用户
# 脚本编写者: chengfeng
# 脚本编写时间: 20250606

ssl_dir=/home/gaming/gamingca

check_group_exists() {
    if getent group "gaming"; then
        return 1
    else
        groupadd -g 2050 gaming
    fi
}

check_user_exists() {
    if id "gaming"; then
        return 1
    else
        useradd -g 2050 -u 2050 -m gaming
    fi
}

create_game_ssl(){
	[ ! -d $ssl_dir ] && mkdir $ssl_dir
	cd $ssl_dir
	openssl genrsa -out gaming.key 2048
	openssl req -new -key gaming.key -out gaming.csr -subj "/CN=gaming/O=gaming"
	openssl x509 -req -in gaming.csr -CA /etc/kubernetes/ssl/ca.pem -CAkey /etc/kubernetes/ssl/ca-key.pem -CAcreateserial -out gaming.crt -days 10000
	openssl x509 -noout -text -in gaming.crt
	cd /home/gaming	&& chown -R gaming:gaming gamingca
}

create_game_k8s_info(){
	runuser -l - gaming -c'
	kubectl config set-cluster kubernetes --server=https://127.0.0.1:6443 --certificate-authority=/etc/kubernetes/ssl/ca.pem --embed-certs=true
	kubectl config set-credentials gaming --client-certificate='${ssl_dir}'/gaming.crt --client-key='${ssl_dir}'/gaming.key --embed-certs=true
	kubectl config set-context gaming --cluster=kubernetes --user=gaming
	kubectl config set current-context gaming
	kubectl config current-context
	kubectl config view'
}

create_game_role(){
cat > ${ssl_dir}/gaming-role.yaml <<EOF
apiVersion: rbac.authorization.k8s.io/v1
kind: Role
metadata:
  namespace: default
  name: gaming-default
rules:
- apiGroups: ["apps"]
  resources: ["deployments","statefulsets"]
  verbs: ["update","patch","get"]
---
apiVersion: rbac.authorization.k8s.io/v1
kind: RoleBinding
metadata:
  name: gaming-rolebinding
  namespace: default
subjects:
- kind: User
  name: gaming
  apiGroup: rbac.authorization.k8s.io
roleRef:
  kind: Role
  name: gaming-default
  apiGroup: rbac.authorization.k8s.io
EOF

kubectl apply -f ${ssl_dir}/gaming-role.yaml
}

main(){
	check_group_exists
	check_user_exists
	create_game_ssl
	create_game_k8s_info
	create_game_role
}

main