Working with Gatekeeper(OPA)
Gatekeeper , is a customizable admission webhook for Kubernetes that enforces policies executed by the Open Policy Agent (OPA), a policy engine for Cloud Native environments hosted by Cloud Native Computing Foundation.
This document demonstrates how to use the Gatekeeper to manage OPA policies.
Prerequisites
Start up Karmada clusters
You just need to clone Karmada repo, and run the following script in the Karmada directory.
hack/local-up-karmada.sh
Gatekeeper Installations
In this case, you will use Gatekeeper v3.7.2. Related deployment files are from here.
Install Gatekeeper APIs on Karmada
Create resource objects for Gatekeeper in karmada controller plane, the content is as follows.
kubectl config use-context karmada-apiserver
Deploy namespace: https://github.com/open-policy-agent/gatekeeper/blob/release-3.7/deploy/gatekeeper.yaml#L1-L9
Deploy Gatekeeper CRDs: https://github.com/open-policy-agent/gatekeeper/blob/release-3.7/deploy/gatekeeper.yaml#L27-L1999
Deploy Gatekeeper secrets: https://github.com/open-policy-agent/gatekeeper/blob/release-3.7/deploy/gatekeeper.yaml#L2261-L2267
Deploy webhook config:
apiVersion: admissionregistration.k8s.io/v1kind: MutatingWebhookConfigurationmetadata:labels:gatekeeper.sh/system: "yes"name: gatekeeper-mutating-webhook-configurationwebhooks:- admissionReviewVersions:- v1- v1beta1clientConfig:#Change the clientconfig from service type to url type cause webhook config and service are not in the same cluster.url: https://gatekeeper-webhook-service.gatekeeper-system.svc:443/v1/mutatefailurePolicy: IgnorematchPolicy: Exactname: mutation.gatekeeper.shnamespaceSelector:matchExpressions:- key: admission.gatekeeper.sh/ignoreoperator: DoesNotExistrules:- apiGroups:- '*'apiVersions:- '*'operations:- CREATE- UPDATEresources:- '*'sideEffects: NonetimeoutSeconds: 1---apiVersion: admissionregistration.k8s.io/v1kind: ValidatingWebhookConfigurationmetadata:labels:gatekeeper.sh/system: "yes"name: gatekeeper-validating-webhook-configurationwebhooks:- admissionReviewVersions:- v1- v1beta1clientConfig:#Change the clientconfig from service type to url type cause webhook config and service are not in the same cluster.url: https://gatekeeper-webhook-service.gatekeeper-system.svc:443/v1/admitfailurePolicy: IgnorematchPolicy: Exactname: validation.gatekeeper.shnamespaceSelector:matchExpressions:- key: admission.gatekeeper.sh/ignoreoperator: DoesNotExistrules:- apiGroups:- '*'apiVersions:- '*'operations:- CREATE- UPDATEresources:- '*'sideEffects: NonetimeoutSeconds: 3- admissionReviewVersions:- v1- v1beta1clientConfig:#Change the clientconfig from service type to url type cause webhook config and service are not in the same cluster.url: https://gatekeeper-webhook-service.gatekeeper-system.svc:443/v1/admitlabelfailurePolicy: FailmatchPolicy: Exactname: check-ignore-label.gatekeeper.shrules:- apiGroups:- ""apiVersions:- '*'operations:- CREATE- UPDATEresources:- namespacessideEffects: NonetimeoutSeconds: 3
You need to change the clientconfig from service type to url type for multi-cluster deployment.
Also, you need to deploy a dummy pod in gatekeeper-system namespace in karmada-apiserver context, because when Gatekeeper generates a policy template CRD, a status object is generated to monitor the status of the policy template, and the status object is bound by the controller Pod through the OwnerReference. Therefore, when the CRD and the controller are not in the same cluster, a dummy Pod needs to be used instead of the controller. The Pod enables the status object to be successfully generated.
For example:
apiVersion: v1kind: Podmetadata:name: dummy-podnamespace: gatekeeper-systemspec:containers:- name: dummy-podimage: nginx:latestimagePullPolicy: Always
Install GateKeeper components on host cluster
kubectl config use-context karmada-host
Deploy namespace: https://github.com/open-policy-agent/gatekeeper/blob/release-3.7/deploy/gatekeeper.yaml#L1-L9
Deploy RBAC resources for deployment: https://github.com/open-policy-agent/gatekeeper/blob/release-3.7/deploy/gatekeeper.yaml#L1999-L2375
Deploy Gatekeeper controllers and secret as kubeconfig:
apiVersion: apps/v1kind: Deploymentmetadata:labels:control-plane: audit-controllergatekeeper.sh/operation: auditgatekeeper.sh/system: "yes"name: gatekeeper-auditnamespace: gatekeeper-systemspec:replicas: 1selector:matchLabels:control-plane: audit-controllergatekeeper.sh/operation: auditgatekeeper.sh/system: "yes"template:metadata:annotations:container.seccomp.security.alpha.kubernetes.io/manager: runtime/defaultlabels:control-plane: audit-controllergatekeeper.sh/operation: auditgatekeeper.sh/system: "yes"spec:automountServiceAccountToken: truecontainers:- args:- --operation=audit- --operation=status- --operation=mutation-status- --logtostderr- --disable-opa-builtin={http.send}- --kubeconfig=/etc/kubeconfigcommand:- /managerenv:- name: POD_NAMESPACEvalueFrom:fieldRef:apiVersion: v1fieldPath: metadata.namespace- name: POD_NAMEvalue: {{POD_NAME}}image: openpolicyagent/gatekeeper:v3.7.2imagePullPolicy: AlwayslivenessProbe:httpGet:path: /healthzport: 9090name: managerports:- containerPort: 8888name: metricsprotocol: TCP- containerPort: 9090name: healthzprotocol: TCPreadinessProbe:httpGet:path: /readyzport: 9090resources:limits:cpu: 1000mmemory: 512Mirequests:cpu: 100mmemory: 256MisecurityContext:allowPrivilegeEscalation: falsecapabilities:drop:- allreadOnlyRootFilesystem: truerunAsGroup: 999runAsNonRoot: truerunAsUser: 1000volumeMounts:- mountPath: /tmp/auditname: tmp-volume- mountPath: /etc/kubeconfigname: kubeconfigsubPath: kubeconfignodeSelector:kubernetes.io/os: linuxpriorityClassName: system-cluster-criticalserviceAccountName: gatekeeper-adminterminationGracePeriodSeconds: 60volumes:- emptyDir: {}name: tmp-volume- name: kubeconfigsecret:defaultMode: 420secretName: kubeconfig---apiVersion: apps/v1kind: Deploymentmetadata:labels:control-plane: controller-managergatekeeper.sh/operation: webhookgatekeeper.sh/system: "yes"name: gatekeeper-controller-managernamespace: gatekeeper-systemspec:replicas: 3selector:matchLabels:control-plane: controller-managergatekeeper.sh/operation: webhookgatekeeper.sh/system: "yes"template:metadata:annotations:container.seccomp.security.alpha.kubernetes.io/manager: runtime/defaultlabels:control-plane: controller-managergatekeeper.sh/operation: webhookgatekeeper.sh/system: "yes"spec:affinity:podAntiAffinity:preferredDuringSchedulingIgnoredDuringExecution:- podAffinityTerm:labelSelector:matchExpressions:- key: gatekeeper.sh/operationoperator: Invalues:- webhooktopologyKey: kubernetes.io/hostnameweight: 100automountServiceAccountToken: truecontainers:- args:- --port=8443- --logtostderr- --exempt-namespace=gatekeeper-system- --operation=webhook- --operation=mutation-webhook- --disable-opa-builtin={http.send}- --kubeconfig=/etc/kubeconfigcommand:- /managerenv:- name: POD_NAMESPACEvalueFrom:fieldRef:apiVersion: v1fieldPath: metadata.namespace- name: POD_NAMEvalue: {{POD_NAME}}image: openpolicyagent/gatekeeper:v3.7.2imagePullPolicy: AlwayslivenessProbe:httpGet:path: /healthzport: 9090name: managerports:- containerPort: 8443name: webhook-serverprotocol: TCP- containerPort: 8888name: metricsprotocol: TCP- containerPort: 9090name: healthzprotocol: TCPreadinessProbe:httpGet:path: /readyzport: 9090resources:limits:cpu: 1000mmemory: 512Mirequests:cpu: 100mmemory: 256MisecurityContext:allowPrivilegeEscalation: falsecapabilities:drop:- allreadOnlyRootFilesystem: truerunAsGroup: 999runAsNonRoot: truerunAsUser: 1000volumeMounts:- mountPath: /certsname: certreadOnly: true- mountPath: /etc/kubeconfigname: kubeconfigsubPath: kubeconfignodeSelector:kubernetes.io/os: linuxpriorityClassName: system-cluster-criticalserviceAccountName: gatekeeper-adminterminationGracePeriodSeconds: 60volumes:- name: certsecret:defaultMode: 420secretName: gatekeeper-webhook-server-cert- name: kubeconfigsecret:defaultMode: 420secretName: kubeconfig---apiVersion: policy/v1beta1kind: PodDisruptionBudgetmetadata:labels:gatekeeper.sh/system: "yes"name: gatekeeper-controller-managernamespace: gatekeeper-systemspec:minAvailable: 1selector:matchLabels:control-plane: controller-managergatekeeper.sh/operation: webhookgatekeeper.sh/system: "yes"---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: gatekeeper-system
You need to fill in the dummy pod created in step 1 to {{ POD_NAME }} and fill in the secret which represents kubeconfig pointing to karmada-apiserver.
Deploy ResourceQuota: https://github.com/open-policy-agent/gatekeeper/blob/release-3.7/deploy/gatekeeper.yaml#L10-L26
Extra steps
After all, we need to copy the secret gatekeeper-webhook-server-cert in karmada-apiserver context to that in karmada-host context to keep secrets stored in etcd and volumes mounted in controller the same.
Run demo
Create k8srequiredlabels template
apiVersion: templates.gatekeeper.sh/v1kind: ConstraintTemplatemetadata:name: k8srequiredlabelsspec:crd:spec:names:kind: K8sRequiredLabelsvalidation:openAPIV3Schema:type: objectdescription: Describe K8sRequiredLabels crd parametersproperties:labels:type: arrayitems:type: stringdescription: A label stringtargets:- target: admission.k8s.gatekeeper.shrego: |package k8srequiredlabelsviolation[{"msg": msg, "details": {"missing_labels": missing}}] {provided := {label | input.review.object.metadata.labels[label]}required := {label | label := input.parameters.labels[_]}missing := required - providedcount(missing) > 0msg := sprintf("you must provide labels: %v", [missing])}
Create k8srequiredlabels constraint
apiVersion: constraints.gatekeeper.sh/v1beta1kind: K8sRequiredLabelsmetadata:name: ns-must-have-gkspec:match:kinds:- apiGroups: [""]kinds: ["Namespace"]parameters:labels: ["gatekeepers"]
Create a bad namespace
kubectl create ns testError from server ([ns-must-have-gk] you must provide labels: {"gatekeepers"}): admission webhook "validation.gatekeeper.sh" denied the request: [ns-must-have-gk] you must provide labels: {"gatekeepers"}