we validate objects with and without namespaces and I always want to print what the current namespace is ... but fallback to "" or some other default value when no namespace is set.
using the naive input.review.object.metadata.namespace
directly fails the rule, so I resorted to
namespace := [input.review.object.metadata.namespace | ""]
which prints an array, kinda ugly but it works ... is there a better solution ?
There isn't a nice operator for it, although there is discussion underway to add one.
Generally the pattern is to use a helper rule/function that has the accessor and a negative one with a default. For example:
https://play.openpolicyagent.org/p/RhZVyJjqOJ Uses..
# If the namespace exists, use it
input_namespace = ns {
ns := input.review.object.metadata.namespace
}
# or if it doesn't, use the string defined here
input_namespace = "whatever-default-value-i-want" {
not input.review.object.metadata.namespace
}
This same kind of pattern can be seen in the wild too, for example in the Gatekeeper library: https://github.com/open-policy-agent/gatekeeper/blob/master/library/general/requiredlabels/src.rego#L3-L10