Working with Kyverno
Kyverno, a Cloud Native Computing Foundation project, is a policy engine designed for Kubernetes. It can validate, mutate, and generate configurations using admission controls and background scans. Kyverno policies are Kubernetes resources and do not require learning a new language. Kyverno is designed to work nicely with tools you already use like kubectl, kustomize, and Git.
This document gives an example to demonstrate how to use Kyverno to manage policies across multiple clusters.
Setup Karmada
To start up Karmada, you can refer to here. If you just want to try Karmada, we recommend building a development environment by hack/local-up-karmada.sh.
git clone https://github.com/karmada-io/karmadacd karmadahack/local-up-karmada.sh
Kyverno Installations
In this case, we will use Kyverno v1.6.3. Related deployment files are from here.
备注
You can choose the version of Kyverno based on that of the cluster where Karmada is installed. See details here. However, Kyverno 1.7.x removes the kubeconfig parameter and does not support out-of-cluster installations. So Kyverno 1.7.x is not able to run with Karmada.
Install Kyverno APIs on Karmada
- Switch to Karmada control plane.
kubectl config use-context karmada-apiserver
- Create resource objects of Kyverno in Karmada controll plane. The content is as follows and does not need to be modified.
Deploy namespace: https://github.com/kyverno/kyverno/blob/release-1.6/config/install.yaml#L1-L12
Deploy configmap: https://github.com/kyverno/kyverno/blob/release-1.6/config/install.yaml#L7751-L7783
Deploy Kyverno CRDs: https://github.com/kyverno/kyverno/blob/release-1.6/config/install.yaml#L12-L7291
Install Kyverno components on host cluster
- Switch to
karmada-hostcontext.
kubectl config use-context karmada-host
- Create resource objects of Kyverno in karmada-host context, the content is as follows.
Deploy namespace: https://github.com/kyverno/kyverno/blob/release-1.6/config/install.yaml#L1-L12
Deploy RBAC resources: https://github.com/kyverno/kyverno/blob/release-1.6/config/install.yaml#L7292-L7750
Deploy Karmada kubeconfig in Kyverno namespace. Fill in the secret which represents kubeconfig pointing to karmada-apiserver, such as ca_crt, client_cer and client_key below.
apiVersion: v1stringData:kubeconfig: |-apiVersion: v1clusters:- cluster:certificate-authority-data: {{ca_crt}}server: https://karmada-apiserver.karmada-system.svc.cluster.local:5443name: kind-karmadacontexts:- context:cluster: kind-karmadauser: kind-karmadaname: karmadacurrent-context: karmadakind: Configpreferences: {}users:- name: kind-karmadauser:client-certificate-data: {{client_cer}}client-key-data: {{client_key}}kind: Secretmetadata:name: kubeconfignamespace: kyverno
Deploy Kyverno controllers and services:
apiVersion: v1kind: Servicemetadata:labels:app: kyvernoapp.kubernetes.io/component: kyvernoapp.kubernetes.io/instance: kyvernoapp.kubernetes.io/name: kyvernoapp.kubernetes.io/part-of: kyvernoapp.kubernetes.io/version: v1.6.3name: kyverno-svcnamespace: kyvernospec:type: NodePortports:- name: httpsport: 443targetPort: httpsnodePort: {{nodePort}}selector:app: kyvernoapp.kubernetes.io/name: kyverno---apiVersion: v1kind: Servicemetadata:labels:app: kyvernoapp.kubernetes.io/component: kyvernoapp.kubernetes.io/instance: kyvernoapp.kubernetes.io/name: kyvernoapp.kubernetes.io/part-of: kyvernoapp.kubernetes.io/version: v1.6.3name: kyverno-svc-metricsnamespace: kyvernospec:ports:- name: metrics-portport: 8000targetPort: metrics-portselector:app: kyvernoapp.kubernetes.io/name: kyverno---apiVersion: apps/v1kind: Deploymentmetadata:labels:app: kyvernoapp.kubernetes.io/component: kyvernoapp.kubernetes.io/instance: kyvernoapp.kubernetes.io/name: kyvernoapp.kubernetes.io/part-of: kyvernoapp.kubernetes.io/version: v1.6.3name: kyvernonamespace: kyvernospec:replicas: 1selector:matchLabels:app: kyvernoapp.kubernetes.io/name: kyvernostrategy:rollingUpdate:maxSurge: 1maxUnavailable: 40%type: RollingUpdatetemplate:metadata:labels:app: kyvernoapp.kubernetes.io/component: kyvernoapp.kubernetes.io/instance: kyvernoapp.kubernetes.io/name: kyvernoapp.kubernetes.io/part-of: kyvernoapp.kubernetes.io/version: v1.6.3spec:affinity:podAntiAffinity:preferredDuringSchedulingIgnoredDuringExecution:- podAffinityTerm:labelSelector:matchExpressions:- key: app.kubernetes.io/nameoperator: Invalues:- kyvernotopologyKey: kubernetes.io/hostnameweight: 1containers:- args:- --filterK8sResources=[Event,*,*][*,kube-system,*][*,kube-public,*][*,kube-node-lease,*][Node,*,*][APIService,*,*][TokenReview,*,*][SubjectAccessReview,*,*][*,kyverno,kyverno*][Binding,*,*][ReplicaSet,*,*][ReportChangeRequest,*,*][ClusterReportChangeRequest,*,*][PolicyReport,*,*][ClusterPolicyReport,*,*]- -v=2- --kubeconfig=/etc/kubeconfig- --serverIP={{nodeIP}}:{{nodePort}}env:- name: INIT_CONFIGvalue: kyverno- name: METRICS_CONFIGvalue: kyverno-metrics- name: KYVERNO_NAMESPACEvalueFrom:fieldRef:fieldPath: metadata.namespace- name: KYVERNO_SVCvalue: kyverno-svc- name: TUF_ROOTvalue: /.sigstoreimage: ghcr.io/kyverno/kyverno:v1.6.3imagePullPolicy: AlwayslivenessProbe:failureThreshold: 2httpGet:path: /health/livenessport: 9443scheme: HTTPSinitialDelaySeconds: 15periodSeconds: 30successThreshold: 1timeoutSeconds: 5name: kyvernoports:- containerPort: 9443name: httpsprotocol: TCP- containerPort: 8000name: metrics-portprotocol: TCPreadinessProbe:failureThreshold: 4httpGet:path: /health/readinessport: 9443scheme: HTTPSinitialDelaySeconds: 5periodSeconds: 10successThreshold: 1timeoutSeconds: 5resources:limits:memory: 384Mirequests:cpu: 100mmemory: 128MisecurityContext:allowPrivilegeEscalation: falsecapabilities:drop:- ALLprivileged: falsereadOnlyRootFilesystem: truerunAsNonRoot: truevolumeMounts:- mountPath: /.sigstorename: sigstore- mountPath: /etc/kubeconfigname: kubeconfigsubPath: kubeconfiginitContainers:- env:- name: METRICS_CONFIGvalue: kyverno-metrics- name: KYVERNO_NAMESPACEvalueFrom:fieldRef:fieldPath: metadata.namespaceimage: ghcr.io/kyverno/kyvernopre:v1.6.3imagePullPolicy: Alwaysname: kyverno-preresources:limits:cpu: 100mmemory: 256Mirequests:cpu: 10mmemory: 64MisecurityContext:allowPrivilegeEscalation: falsecapabilities:drop:- ALLprivileged: falsereadOnlyRootFilesystem: truerunAsNonRoot: truesecurityContext:runAsNonRoot: trueserviceAccountName: kyverno-service-accountvolumes:- emptyDir: {}name: sigstore- name: kubeconfigsecret:defaultMode: 420secretName: kubeconfig---
For multi-cluster deployment, we need to add the config of --serverIP which is the address of the webhook server. So you need to ensure that the network from nodes in Karmada control plane to those in karmada-host cluster is connected and expose Kyverno controller pods to control plane, for example, using nodePort above.
Run demo
Create require-labels ClusterPolicy
ClusterPolicy is a CRD which Kyverno offers to support different kinds of rules. Here is an example ClusterPolicy which means that you must create pod with app.kubernetes.io/name label. You can use the following commands to create it in Karmada control plane.
kubectl config use-context karmada-apiserver
kubectl create -f- << EOFapiVersion: kyverno.io/v1kind: ClusterPolicymetadata:name: require-labelsspec:validationFailureAction: enforcerules:- name: check-for-labelsmatch:any:- resources:kinds:- Podvalidate:message: "label 'app.kubernetes.io/name' is required"pattern:metadata:labels:app.kubernetes.io/name: "?*"EOF
The output is similar to:
clusterpolicy.kyverno.io/require-labels created
Create a bad deployment without labels
kubectl create deployment nginx --image=nginx
The output is similar to:
error: failed to create deployment: admission webhook "validate.kyverno.svc-fail" denied the request:policy Deployment/default/nginx for resource violation:require-labels:autogen-check-for-labels: 'validation error: label ''app.kubernetes.io/name'' isrequired. rule autogen-check-for-labels failed at path /spec/template/metadata/labels/app.kubernetes.io/name/'