Howard Jones
Howard Jones

Reputation: 49

Can OPA Gatekeeper be used to audit K8s PodDisruptionBudget status fields?

We are looking to use OPA gatekeeper to audit K8s PodDisruptionBudget (PDB) objects. In particular, we are looking to audit the number of disruptionsAllowed within the status field.

I believe this field will not be available at point of admission since it is calculated and added by the apiserver once the PDB has been applied to the cluster.

It appears that for e.g Pods, the status field is passed as part of the AdmissionReview object [1]. In that particular example it appears that only the pre-admission status fields make it into the AdmissionReview object.

1.) Is it possible to audit on the current in-cluster status fields in the case of PDBs?

2.) Given the intended use of OPA Gatekeeper as an admission controller, would this be considered an anti-pattern?

[1] https://www.openpolicyagent.org/docs/latest/kubernetes-introduction/

Upvotes: 4

Views: 810

Answers (1)

Will Beason
Will Beason

Reputation: 3561

This is actually quite reasonable, and is one of the use cases of Audit. You just need to make sure audit is enabled and spec.enforcementAction: dryrun is set in the Constraint.

Here is an example of what the ConstratintTemplate's Rego would look like. OPA Playground.

deny[msg] {
    value := input.request.object.status.disruptionsAllowed
    value > maxDisruptionsAllowed

    msg := sprintf("status.disruptionsAllowed must be <%v> or fewer; found <%v>", [maxDisruptionsAllowed, value])
}

In the specific Constraint, make sure to set enforcementAction to dryrun so the Constraint does not prevent k8s from updating the status field. For example:

apiVersion: constraints.gatekeeper.sh/v1beta1
kind: K8sAllowedPodDisruptions
metadata:
  name: max-disruptions
spec:
  enforcementAction: dryrun
  match:
    kinds:
      - apiGroups: [""]
        kinds: ["PodDisruptionBudget"]
    namespaces:
      - "default"
  parameters:
    maxDisruptionsAllowed:
      - 10

If you forget to set enforcementAction, k8s will be unable to update the status field of the PodDisruptionBudget.

Upvotes: 1

Related Questions