使用证书认证方式配置k8s全局只读权限

吾生也有涯,而知也无涯。这篇文章主要讲述使用证书认证方式配置k8s全局只读权限相关的知识,希望能为你提供帮助。
需求:给开发配置全局只读权限,即只能查看日志,事件等一切只读权限,并且限定namespace。另外需要可以满足开发可以登陆pod的需求。开发拿着这个config文件就可以访问k8s

#!/bin/bash

CLUSTERNAME=kube-jenkins-nonlive
NAMESPACE=jenkins
USERNAME=$1
API_SERVER_URL="https://x.x.x.x:6443"
GROUPNAME=jenkins-dev
CERT_PATH=/etc/kubernetes/pki

openssl genrsa -out $USERNAME.key 2048

CSR_FILE=$USERNAME.csr
KEY_FILE=$USERNAME.key

openssl req -new -key $KEY_FILE -out $CSR_FILE -subj "/CN=$USERNAME/O=$GROUPNAME"

CERTIFICATE_NAME=$USERNAME.$NAMESPACE

cat < < EOF | kubectl create -f -
apiVersion: certificates.k8s.io/v1beta1
kind: CertificateSigningRequest
metadata:
name: $CERTIFICATE_NAME
spec:
groups:
- system:authenticated
request: $(cat $CSR_FILE | base64 | tr -d \\n)
usages:
- digital signature
- key encipherment
- client auth
EOF

kubectl certificate approve $CERTIFICATE_NAME

CRT_FILE=$USERNAME.crt

kubectl get csr $CERTIFICATE_NAME -o jsonpath=.status.certificate| base64 -d > $CRT_FILE

cat < < EOF | kubectl create -f -
kind: Role
apiVersion: rbac.authorization.k8s.io/v1
metadata:
namespace: $NAMESPACE
name: jenkins-dev
rules:
- apiGroups: ["*"]
resources: ["*"]
verbs: ["get", "list", "watch"] # You can also use ["*"]
- apiGroups: [""]
resources: ["pods/exec"]
verbs: ["create"]
EOF


cat < < EOF | kubectl create -f -
kind: RoleBinding
apiVersion: rbac.authorization.k8s.io/v1
metadata:
name: $USERNAME-jenkins-dev-binding
namespace: $NAMESPACE
subjects:
- kind: User
name: $USERNAME
apiGroup: ""
roleRef:
kind: Role
name: jenkins-dev
apiGroup: ""
EOF

kubectl config set-cluster $CLUSTERNAME --server=$API_SERVER_URL \\
--certificate-authority=$CERT_PATH/ca.crt \\
--embed-certs=true --kubeconfig=./"$USERNAME".config

kubectl config set-credentials $USERNAME \\
--client-certificate=$(pwd)/$CRT_FILE\\
--client-key=$(pwd)/$KEY_FILE --kubeconfig=./"$USERNAME".config

kubectl config set-context $USERNAME-context \\
--cluster=$CLUSTERNAME \\
--namespace=$NAMESPACE \\
--user=$USERNAME --kubeconfig=./"$USERNAME".config

CLIENT_CERTIFICATE_DATA=https://www.songbingjia.com/android/`cat $(pwd)/$CRT_FILE |base64|tr -d"\\n"`
CLIENT_KEY_DATA=https://www.songbingjia.com/android/`cat $(pwd)/$KEY_FILE |base64|tr -d"\\n"`

sed -i "s/.*client-certificate.*/client-certificate-data: $CLIENT_CERTIFICATE_DATA/g" $(pwd)/"$USERNAME".config
sed -i "s/.*client-key.*/client-key-data: $CLIENT_KEY_DATA/g" $(pwd)/"$USERNAME".config
sed -i "s/.*current-context.*/current-context: $USERNAME-context/g" $(pwd)/"$USERNAME".config

【使用证书认证方式配置k8s全局只读权限】


    推荐阅读