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

Posted 庭中有奇树

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了使用证书认证方式配置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=`cat $(pwd)/$CRT_FILE |base64|tr -d "\\n"`
CLIENT_KEY_DATA=`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全局只读权限的主要内容,如果未能解决你的问题,请参考以下文章

十一,k8s集群访问控制之ServicAccount

k8s认证授权

k8s系列-13-生成证书和各组件的认证配置

k8s使用自定义证书将客户端认证接入到API Server

k8s 权限理解

K8s:通过 kubectl 插件 rakkess 查看集群 RBAC授权信息