我们验证有和没有命名空间的对象,我总是想打印当前的命名空间是什么......但是当没有设置命名空间时回退到“”或其他一些默认值。
使用 naiveinput.review.object.metadata.namespace
直接违反了规则,所以我求助于
namespace := [input.review.object.metadata.namespace | ""]
它打印一个数组,有点难看,但它可以工作......有更好的解决方案吗?
我们验证有和没有命名空间的对象,我总是想打印当前的命名空间是什么......但是当没有设置命名空间时回退到“”或其他一些默认值。
使用 naiveinput.review.object.metadata.namespace
直接违反了规则,所以我求助于
namespace := [input.review.object.metadata.namespace | ""]
它打印一个数组,有点难看,但它可以工作......有更好的解决方案吗?
它没有一个好的运算符,尽管正在讨论添加一个。
通常,该模式是使用具有访问器的辅助规则/函数和具有默认值的否定规则/函数。例如:
https://play.openpolicyagent.org/p/RhZVyJjqOJ 使用..
# 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
}
这种模式也可以在野外看到,例如在 Gatekeeper 库中:https ://github.com/open-policy-agent/gatekeeper/blob/master/library/general/requiredlabels/src.rego# L3-L10