k8s operator添加webhook
Operator中的webhook,其作用与过滤器类似,外部对CRD资源的变更,在Controller处理之前都会交给webhook提前处理,kubernetes官方博客明确指出webhook可以做两件事:修改(mutating)和验证(validating)。
kubebuilder为我们提供了生成webhook的基础文件和代码的工具,与制作API的工具类似,极大地简化了工作量,咱们只需聚焦业务实现即可;
基于kubebuilder制作的webhook和controller,如果是同一个资源,那么它们在同一个进程中;
一、使用kubebuiler创建webhook
[root@k8s-node4 demo-operator]# kubebuilder create webhook --group apps --version v1beta1 --kind MyDaemonset --defaulting --programmatic-validation Writing kustomize manifests for you to edit... Writing scaffold for you to edit... api/v1beta1/mydaemonset_webhook.go Update dependencies: $ go mod tidy Running make: $ make generate test -s /data/demo-operator/bin/controller-gen && /data/demo-operator/bin/controller-gen --version | grep -q v0.11.1 || \ GOBIN=/data/demo-operator/bin go install sigs.k8s.io/controller-tools/cmd/[email protected] /data/demo-operator/bin/controller-gen object:headerFile="hack/boilerplate.go.txt" paths="./..." Next: implement your new Webhook and generate the manifests with: $ make manifests
[root@k8s-node4 demo-operator]# ll config/
total 32
drwx------ 2 root root 4096 Feb 25 22:26 certmanager #新生成
drwx------ 4 root root 4096 Feb 25 20:47 crd
drwx------ 2 root root 4096 Feb 25 22:26 default
drwx------ 2 root root 4096 Feb 25 20:23 manager
drwx------ 2 root root 4096 Feb 25 20:23 prometheus
drwx------ 2 root root 4096 Feb 25 20:47 rbac
drwx------ 2 root root 4096 Feb 25 21:21 samples
drwx------ 2 root root 4096 Feb 25 22:26 webhook #新生成
二、添加image字段校验逻辑
修改api/v1beta1/mydaemonset_webhook.go文件,添加逻辑,若image字段为空,则报错
三、配置webhook及certmanager
修改config/default/kustomization.yaml,取消webhook和certmanager相关注释,启动webhook相关功能;
打开vars下所有注释
四、运行webhook
webhook必须部署在k8s中,此时local run的方法已经不生效,此时我们需要构建镜像,将其部署在k8s中;
kubebuilder提供了相关的指令make docker-build(将kubebuilder的controller编译成二进制文件,然后放到容器镜像中) 和make docker-push(将镜像推到dockerhub上)
标签:25,Feb,webhook,------,operator,k8s,root From: https://www.cnblogs.com/wushaoyu/p/17155686.html