Search code examples
kuberneteswebhookskube-apiserver

Kubernetes - Admission webhook - validate scale operatoin in deployments


I would like to validate deployments based on custom logic before scale. I created an admission webhook to do that, but unfortunately the scale operation is undetected by the webook.

apiVersion: admissionregistration.k8s.io/v1
kind: ValidatingWebhookConfiguration
metadata:
  name: deployment-validator
webhooks:
  - admissionReviewVersions:
      - v1
    clientConfig:
      service:
        name: example-name
        namespace: example-namespace
        path: /validate-deployment
        port: 9443
    failurePolicy: Ignore
    matchPolicy: Equivalent
    name: validation.deploy.example-domain.com
    namespaceSelector: {}
    objectSelector: {}
    rules:
      - apiGroups:
          - apps
        apiVersions:
          - v1
        operations:
          - '*'
        resources:
          - deployment
        scope: '*'
    sideEffects: None
    timeoutSeconds: 10

If I CREATE or UPDATE the deployment, the action is detected by the webhook server, also if I PATCH (kubectl patch ...). Unfortunately if I use kubectl scale ..., the webhook server does not detect the action, and I'm unable to validate the request.

How can I resolve this issue?


Solution

  • When you run kubectl scale you are not actually patching the Deployment resource, but you are editing a subresource named Scale instead.

    This is the API doc entry of the scale call: https://kubernetes.io/docs/reference/generated/kubernetes-api/v1.24/#replace-scale-deployment-v1-apps

    PUT /apis/apps/v1/namespaces/{namespace}/deployments/{name}/scale
    

    Also, I think you need the plural name for your resouce. So you might have to change the rule in your admission controller like this:

        rules:
          - apiGroups:
              - apps
            apiVersions:
              - v1
            operations:
              - '*'
            resources:
              - deployments/scale
            scope: '*'
    

    and that should work.