在之前介绍kube-apiserver的文章里面有介绍apiserver的处理请求的过程,这里再粘贴一下这张图,apiserver在执行完认证和授权后就会调用这个 Mutating Webhook,然后 Mutating Webhook 接收请求处理后再把修改后对象返给apiserver ,所以我们可以通过Mutating Webhook 修改k8s对象。
下面我们通过一个Demo 演示如何编写一个 Mutating Webhook。这个Demo里面我们希望给Pod 加上一个 configmap 的挂载。
首先我们得告诉apiserver 我们启动了一个Mutating webhook,这个webhook 服务的地址是在default namespace下,名字叫做hello-webhook-service, 访问路径是 /mutate。
apiVersion: admissionregistration.k8s.io/v1
kind: MutatingWebhookConfiguration
metadata:
name: "hello-webhook.leclouddev.com"
webhooks:
- name: "hello-webhook.leclouddev.com"
objectSelector:
matchLabels:
hello: "true"
rules:
- apiGroups: [""]
apiVersions: ["v1"]
operations: ["CREATE"]
resources: ["pods"]
scope: "Namespaced"
clientConfig:
service:
namespace: "default"
name: "hello-webhook-service"
path: /mutate
admissionReviewVersions: ["v1", "v1beta1"]
sideEffects: None
timeoutSeconds: 10
并且rules 定义在pod 创建的时候才会被调用,这样每次当有pod 创建的时候,就可以调用这个接口了。那么接下来我们就创建这个服务,这个服务的名称就是上面定义的hello-webhook-service。
apiVersion: v1
kind: Service
metadata:
name: hello-webhook-service
spec:
type: ClusterIP
selector:
app: hello-webhook
ports:
- protocol: TCP
port: 443
targetPort: 8000
服务有了,还需要后端Pod,我们通过Deployment方式部署这个webhook Pod。
apiVersion: apps/v1
kind: Deployment
metadata:
name: hello-webhook-deployment
labels:
app: hello-webhook
spec:
replicas: 1
selector:
matchLabels:
app: hello-webhook
template:
metadata:
labels:
app: hello-webhook
spec:
containers:
- name: hello-webhook
image: CONTAINER_IMAGE
ports:
- containerPort: 8000
volumeMounts:
- name: hello-tls-secret
mountPath: "/tls"
readOnly: true
resources:
limits:
memory: "128Mi"
cpu: "500m"
volumes:
- name: hello-tls-secret
secret:
secretName: hello-tls-secret
上面的 CONTAINER_IMAGE 就是我们需要开发的Pod。apiserver会调用这个pod 里面的HTTP服务。主体代码如下:
func (app *App) HandleMutate(w http.ResponseWriter, r *http.Request) {
//给跑pod 添加一个volume
pod.Spec.Volumes = append(pod.Spec.Volumes, corev1.Volume{
Name: "hello-volume",
VolumeSource: corev1.VolumeSource{
ConfigMap: &corev1.ConfigMapVolumeSource{
LocalObjectReference: corev1.LocalObjectReference{
Name: "hello-configmap",
},
},
},
})
//给每个容器 添加 volumeount
for i := 0; i < len(pod.Spec.Containers); i++ {
pod.Spec.Containers[i].VolumeMounts = append(pod.Spec.Containers[i].VolumeMounts, corev1.VolumeMount{
Name: "hello-volume",
MountPath: "/etc/config",
})
}
这样我们就完成一个 Mutating webhook 的开发和配置了。
页面更新:2024-06-21
本站资料均由网友自行发布提供,仅用于学习交流。如有版权问题,请与我联系,QQ:4156828
© CopyRight 2020-2024 All Rights Reserved. Powered By 71396.com 闽ICP备11008920号-4
闽公网安备35020302034903号