Trouble creating a kyverno policy to invalidate misplaced elements (bad practices)?

13 views Asked by At

I'm trying to write a kyverno policy to invalidate misplaced elements in the deployment's structure (strategy in .spec.template.spec and not .spec in a deployment, in my case) i know the k8s api does the validation but i need the policy for it to happen on the pipeline's level.

Here's the policy validate-deployment-strategy.yaml i wrote i tried it 2 ways:

1st version:

apiVersion: kyverno.io/v1
kind: ClusterPolicy
metadata:
  name: validate-deployment-strategy
spec:
  validationFailureAction: Enforce
  background: true
  rules:
  - name: validate-deployment-strategy
    match:
      resources:
        kinds:
        - DaemonSet
        - Deployment
        - Job
        - StatefulSet
    validate:
      message: "'strategy' should be in .spec, not .spec.template.spec"
      pattern:
        =(spec):
          =(template):
            =(spec):
              =(strategy): 
                type: "!*"

2nd version :

apiVersion: kyverno.io/v1
kind: ClusterPolicy
metadata:
  name: validate-deployment-strategy
spec:
  validationFailureAction: Enforce
  background: true
  rules:
  - name: validate-deployment-strategy
    match:
      resources:
        kinds:
        - DaemonSet
        - Deployment
        - Job
        - StatefulSet
    validate:
      message: "'strategy' should be in .spec, not .spec.template.spec"
      pattern:
        spec:
          template:
            spec:
              strategy: {}

when testing the policy on a deployment :

apiVersion: apps/v1
kind: Deployment
metadata:
  name: nginx-deployment
  labels:
    app: nginx
spec:
  replicas: 3
  selector:
    matchLabels:
      app: nginx
  template:
    metadata:
      labels:
        app: nginx
    spec:
      strategy:
        type: RollingUpdate
      containers:
      - name: nginx
        image: nginx:1.14.2
        ports:
        - containerPort: 80

the policy triggers when strategy is in .spec.template.spec or in it's write place .spec and I dont understand the issue (new to kyverno)

i tried it locally through the commands :

kubectl apply -f validate-deployment-strategy.yaml kubectl apply -f deployment.yaml --validate=false

0

There are 0 answers