Rego support
Datree supports writing custom rules in the Rego language, by utilizing a custom JSON Schema keyword.
Supported version
Writing custom rules in Rego is supported in CLI version 1.8.41 and above.
Required properties
In addition to the basic required format, a Rego custom rule has the following requirements:
- The
schemaproperty must have a property namedregoDefinition. - The
regoDefinitionproperty must have a property namedcodethat contains the Rego logic of the rule.- The
codeproperty must be a string that contains aviolationfunction definition. - The
violationfunction must return a boolean value.
- The
- The
regoDefinitionproperty may have a property namedlibs, which is an array of library functions that will be available to the Rego package.
Online Rego validation
Ensure the validity of your rules and test them against your resources using the Rego playground.
Example:
The following schema requires the tested Deployment resource to have a billing label:
schema:
regoDefinition:
libs:
- |
package lib.helpers
check_if_missing(missing) = isMissing {
isMissing := count(missing) > 0
}
code: |
package requiredlabels
import data.lib.helpers
violation[labelIsMissing] {
input.kind == "Deployment"
provided := {label | input.metadata.labels[label]}
required := {"billing"}
missing := required - provided
labelIsMissing := helpers.check_if_missing(missing)
}
Constraints
In the above example, the constraint input.kind == "Deployment" is a part of the Rego logic.
You can also write such a constraint in JSON schema and write the rest of the logic in Rego:
schema:
# Constraint - enforce rule only on `Deployment` resources
if:
properties:
kind:
type: string
enum:
- Deployment
then:
regoDefinition:
libs:
- |
package lib.helpers
check_if_missing(missing) = isLabelMissing {
isLabelMissing := count(missing) > 0
}
code: |
package requireBillingLabel
import data.lib.helpers
violation[isLabelMissing] {
provided := {label | input.metadata.labels[label]}
required := {"billing"}
missing := required - provided
isLabelMissing := helpers.check_if_missing(missing)
}