6. Create an Admissionregistration object that calls this Service for the right API action and Labeled Namespace
Now is the interesting part. Create the object that will register our application as a webhook to validate deployments.
First, we will need to charge the ca_bundle that we create in step 1 as an environment variable.
CA_BUNDLE=$(cat certs/ca_bunddle)
Once that is set we can generate the webhook file:
cat > webhook.yml << EOF
apiVersion: admissionregistration.k8s.io/v1
kind: ValidatingWebhookConfiguration
metadata:
name: k8s-admission-demo
webhooks:
- name: k8s-admission-demo.kubernetes.io
clientConfig:
service:
name: k8s-admission-demo
namespace: default
path: "/validate"
caBundle: "${CA_BUNDLE}"
failurePolicy: Fail
rules:
- operations: ["CREATE"]
apiGroups: ["apps"]
apiVersions: ["v1"]
resources: ["deployments"]
namespaceSelector:
matchLabels:
k8s-admission-demo.kubernetes.io/assert-deployment-more-than-one-replicas: "true"
sideEffects: None
admissionReviewVersions:
- v1
EOF
And create the object in Kubernetes:
kubectl create -f webhook.yml
Here are some observations about each field of the webhook object:
- name - It needs to be a domain
- clientConfig - It needs to point to the service of our application and we need to provide the public certificate of the CA authority used to sign the application certificate.
- rules - A combination of Operations and Resource API groups that we want to validate. Only CREATE, UPDATE, DELETE and CONNECT are valid.
- namespaceSelector - Specification to limit the scope of this admission controller. The chosen label was
k8s-admission-demo.kubernetes.io/assert-deployment-more-than-one-replicas=true
. - failurePolicy - Determines what to do in case code fails during validation. The default behavior is to fail the request. (Fail/Ignore)
You can learn more about each field with the explain command:
kubectl explain ValidatingWebhookConfiguration.webhooks.name
kubectl explain ValidatingWebhookConfiguration.webhooks.clientConfig
kubectl explain ValidatingWebhookConfiguration.webhooks.rules
kubectl explain ValidatingWebhookConfiguration.webhooks.namespaceSelector
kubectl explain ValidatingWebhookConfiguration.webhooks.sideEffects
kubectl explain ValidatingWebhookConfiguration.webhooks.admissionReviewVersions
kubectl explain ValidatingWebhookConfiguration.webhooks.failurePolicy
kubectl explain ValidatingWebhookConfiguration.webhooks