创建对指定namespace有所有权限的kube-config
#!/bin/bash## This Script based on https://jeremievallee.com/2018/05/28/kubernetes-rbac-namespace-user.html# K8s'RBAC doc: https://kubernetes.io/docs/reference/access-authn-authz/rbac# Gitlab'CI/CD doc: hhttps://docs.gitlab.com/ee/user/permissions.html#running-pipelines-on-protected-branches## In honor of the remarkable WindsonBASEDIR="$(dirname "$0")"folder="$BASEDIR/kube_config"echo -e "All namespaces is here: \n$(kubectl get ns|awk 'NR!=1{print $1}')"echo "endpoint server if local network you can use $(kubectl cluster-info |awk '/Kubernetes/{print $NF}')"namespace=$1endpoint=$(echo "$2" | sed -e 's,https\?://,,g')if [[ -z "$endpoint" || -z "$namespace" ]]; thenecho "Use "$(basename "$0")" NAMESPACE ENDPOINT";exit 1;fiif ! kubectl get ns|awk 'NR!=1{print $1}'|grep -w "$namespace";then kubectl create ns "$namespace";else echo "namespace: $namespace was exist." ;fiecho "---apiVersion: v1kind: ServiceAccountmetadata:name: $namespace-usernamespace: $namespace---kind: RoleapiVersion: rbac.authorization.k8s.io/v1beta1metadata:name: $namespace-user-full-accessnamespace: $namespacerules:- apiGroups: ['', 'extensions', 'apps', 'metrics.k8s.io']resources: ['*']verbs: ['*']- apiGroups: ['batch']resources:- jobs- cronjobsverbs: ['*']---kind: RoleBindingapiVersion: rbac.authorization.k8s.io/v1beta1metadata:name: $namespace-user-viewnamespace: $namespacesubjects:- kind: ServiceAccountname: $namespace-usernamespace: $namespaceroleRef:apiGroup: rbac.authorization.k8s.iokind: Rolename: $namespace-user-full-access---# https://kubernetes.io/zh/docs/concepts/policy/resource-quotas/apiVersion: v1kind: ResourceQuotametadata:name: $namespace-compute-resourcesnamespace: $namespacespec:hard:pods: "10"services: "10"persistentvolumeclaims: "5"requests.cpu: "1"requests.memory: 2Gilimits.cpu: "2"limits.memory: 4Gi" | kubectl apply -f -kubectl -n $namespace describe quota $namespace-compute-resourcesmkdir -p $foldertokenName=$(kubectl get sa $namespace-user -n $namespace -o "jsonpath={.secrets[0].name}")token=$(kubectl get secret $tokenName -n $namespace -o "jsonpath={.data.token}" | base64 --decode)certificate=$(kubectl get secret $tokenName -n $namespace -o "jsonpath={.data['ca\.crt']}")echo "apiVersion: v1kind: Configpreferences: {}clusters:- cluster:certificate-authority-data: $certificateserver: https://$endpointname: $namespace-clusterusers:- name: $namespace-useruser:as-user-extra: {}client-key-data: $certificatetoken: $tokencontexts:- context:cluster: $namespace-clusternamespace: $namespaceuser: $namespace-username: $namespacecurrent-context: $namespace" > $folder/$namespace.kube.conf
