Rego based OPA Policy for restricting Argo CD applications being created in default Argo CD project is not working with Gatekeeper. I have tried multiple combinations of api versions and kinds in the constraint as well. Constraint template and constraint gets applied successfully but the creation of Argo Application still goes through successfully without being restricted which was expected.
Gatekeeper version: 3.8.1 Kubernetes version: 1.22.9
ConstraintTemplate
apiVersion: templates.gatekeeper.sh/v1
kind: ConstraintTemplate
metadata:
name: k8snoappindefaultargoproject
annotations:
description: >-
Restricts any ArgoCD Applications to be created in default ArgoCD project
spec:
crd:
spec:
names:
kind: K8sNoAppInDefaultArgoProject
targets:
- target: admission.k8s.gatekeeper.sh
rego: |
package k8snoappindefaultargoproject
violation[{"msg": def_msg}] {
name := input.review.object.metadata.name
mySpec := input.review.object.spec
mySpec.project == "default"
def_msg := sprintf("Error: `%v` ArgoCD Application is not permitted to use default ArgoCD project.",[name])
}
Constraint
apiVersion: constraints.gatekeeper.sh/v1beta1
kind: K8sNoAppInDefaultArgoProject
metadata:
name: no-app-in-default-argo-project
spec:
enforcementAction: deny
match:
kinds:
- apiGroups: ["argoproj.io/v1alpha1"]
kinds: ["Application"]
Update:
We were able to resolve this by refactoring the rego code as below. Maybe that's how rego works that we need to assign the extracted value to a variable before comparing.
name := input.review.object.metadata.name
mySpec := input.review.object.spec
> myProject := mySpec.project
> myProject == "default"
def_msg := sprintf("Error: `%v` ArgoCD Application is not permitted to use default ArgoCD project.",[name])