imagepolicywebhook
imagePolicyWebhook
imagePolicyWebhook是一个评估image的准入控制器。需要启动一个https的服务来执行该动作
【功能实践】
-
为webhook 生成ssl 证书
生成server.csr 和 server-key.pem
cat <<EOF | cfssl genkey - | cfssljson -bare server { "hosts": [ "image-bouncer-webhook.default.svc", "image-bouncer-webhook.default.svc.cluster.local", "image-bouncer-webhook.default.pod.cluster.local", "192.0.2.24", "10.0.34.2" ], "CN": "system:node:image-bouncer-webhook.default.pod.cluster.local", "key": { "algo": "ecdsa", "size": 256 }, "names": [ { "O": "system:nodes" } ] } EOF
提交CertificateSigningRequest 请求生成server.crt
cat <<EOF | kubectl apply -f - apiVersion: certificates.k8s.io/v1 kind: CertificateSigningRequest metadata: name: image-bouncer-webhook.default spec: request: $(cat server.csr | base64 | tr -d '\n') signerName: kubernetes.io/kubelet-serving usages: - digital signature - key encipherment - server auth EOF
kubectl certificate approve image-bouncer-webhook.default
root@master01:~# kubectl get csr NAME AGE SIGNERNAME REQUESTOR REQUESTEDDURATION CONDITION image-bouncer-webhook.default 2m12s kubernetes.io/kubelet-serving kubernetes-admin <none> Approved,Issued
kubectl get csr image-bouncer-webhook.default -o jsonpath='{.status.certificate}' | base64 --decode >server.crt
cp server.crt /etc/kubernetes/kube-image-bouncer/pki/server.crt
chown -R 1000:1000 server*
-
启动webhook服务
echo "127.0.0.1 image-bouncer-webhook.default.svc" >> /etc/hosts
docker run --rm \ -v `pwd`/server-key.pem:/certs/server-key.pem:ro 、 -v `pwd`/server.crt:/certs/server.crt:ro 、 -p 1323:1323 \ --network host \ kainlite/kube-image-bouncer -k /certs/server-key.pem -c /certs/server.crt
-
修改apiserver配置文件,并重启apiserver
--admission-control-config-file=/etc/kubernetes/kube-image-bouncer/admission_configuration.yaml --enable-admission-plugins=ImagePolicyWebhook
# /etc/kubernetes/kube-image-bouncer/admission_configuration.yaml imagePolicy: kubeConfigFile: "/etc/kubernetes/kube-image-bouncer/kube-image-bouncer.yml" # 以秒计的时长,控制批准请求的缓存时间 allowTTL: 50 # 以秒计的时长,控制拒绝请求的缓存时间 denyTTL: 50 # 以毫秒计的时长,控制重试间隔 retryBackoff: 500 # 确定 Webhook 后端失效时的行为 defaultAllow: true
# cat /etc/kubernetes/kube-image-bouncer/kube-image-bouncer.yml apiVersion: v1 kind: Config clusters: - cluster: certificate-authority: /etc/kubernetes/kube-image-bouncer/pki/server.crt server: https://image-bouncer-webhook.default.svc:1323/image_policy name: bouncer_webhook contexts: - context: cluster: bouncer_webhook user: api-server name: bouncer_validator current-context: bouncer_validator preferences: {} users: - name: api-server user: client-certificate: /etc/kubernetes/pki/apiserver.crt client-key: /etc/kubernetes/pki/apiserver.key
-
功能验证
root@master01:~# kubectl run test --image=busybox Error from server (Forbidden): pods "test" is forbidden: image policy webhook backend denied one or more images: Images using latest tag are not allowed
参考
Kubernetes 镜像策略 webhook 解释 - Kubernetes、CI/CD、Git、Linux、容器、Golang...和更多 (techsquad.rocks)