Tech

How to Restrict Container Registries per Namespace with Kyverno

24. May 2022

We have recently received a request from a customer, asking us to restrict the container registries that could be used to deploy images from in their OpenShift 4 cluster.

We could have added such configuration directly at node level, as explained in Red Hat’s documentation; it’s indeed possible to whitelist registries on repository and tag level, but that would have forced us to keep all those whitelists updated with those our Project Syn components regularly use.

We have instead chosen to use Kyverno for this task: it allows us to enforce the limitations on a per-namespace level, with much more flexibility and maintanability.

This is a ClusterPolicy object for Kyverno, adapted from the solution we provided to our customer, showing how we can restrict the limitation to some namespaces, so that containers can be pulled only from some specific registries.

apiVersion: kyverno.io/v1
kind: ClusterPolicy
metadata:
  name: restrict-registries
  annotations:
    policies.kyverno.io/title: Restrict Image Registries
    policies.kyverno.io/subject: Pod
    policies.kyverno.io/description: >-
      Restrict image pulling only to whitelisted registries
spec:
  validationFailureAction: enforce
  background: true
  rules:
  - name: validate-registries
    match:
      all:
      - resources:
          kinds:
          - Pod
          namespaces:
          - "namespace-wildcard-*"
    validate:
      message: "Image registry not whitelisted"
      pattern:
        spec:
          containers:
          - image: "registry.example.com/* | hub.docker.com/some-username/*"

Aarno Aukia

Aarno is Co-Founder of VSHN AG and provides technical enthusiasm as a Service as CTO.

Contact us

Our team of experts is available for you. In case of emergency also 24/7.

Contact us