Monday, December 09, 2019

Tip: OPA Rego error minus: operand 1 must be one of {number, set} but got string

Symptom:

    We start to use OPA gatekeeper for our kubernetes clusters. Refer https://github.com/open-policy-agent/gatekeeper
    When we code some policies for kubernetes using OPA (open policy agent) Rego , the part of code is like below
violation[{"msg": msg}] {
          provided := input.review.object.spec.nodeSelector[label]
          required := input.parameters.labels[_].key
          missing := required - provided
          expected :=  input.parameters.labels[_]
          count(missing) > 0
          msg := sprintf("Missing nodeSelector label <%v: %v>, or too many nodeSelector labels,only 1 nodeSelector lable is allowed.< %v:%v>",[expected.key,expected.allowedvalue,provided,required])

We get error:
eval_type_error: minus: operand 1 must be one of {number, set} but got string): error when creating "access-pod.yaml": admission webhook "validation.gatekeeper.sh" denied the request: admission.k8s.gatekeeper.sh: templates["admission.k8s.gatekeeper.sh"]["K8sAllowedNodeselector"]:5: eval_type_error: minus: operand 1 must be one of {number, set} but got string

Solution:

        missing := required - provided , all variables are string, minus operator can't deal with string, so we need to convert them into number or set
So the right code is
provided := {label | input.review.object.spec.nodeSelector[label]}
required := {label | label := input.parameters.labels[_].key}

No comments: