VK Cloud logo
Updated at April 15, 2024   08:50 AM

Configuring mandatory labels

With Gatekeeper you can set a constraint that will require a specific label for created Kubernetes resources. For example, this constraint can be useful if company policies require the creator name of any Kubernetes resources to facilitate auditing and parsing of potential incidents.

To demonstrate how Gatekeeper works, the following will be created:

  • A constraint template and its corresponding constraint. It will require a creator-name label in Kubernetes resources that are created in any namespaces (except system namespaces).
  • A few Kubernetes resources to test how the constraint works.

Preparatory steps

  1. Create a Kubernetes cluster of the most current version.

    Choose the cluster parameters at your own discretion.

  2. Make sure that you can connect to the cluster with kubectl.

Create a constraint that checks labels

  1. Create a constraint template:

    1. Create a constraint template manifest.

      Use the contents of this file. This is a ready-made template K8sRequiredLabels from Gatekeeper library, which checks if the Kubernetes resource has the specified labels.

    2. Create a restriction template based on the template manifest:

      kubectl apply -f template.yaml
  2. Create a constraint:

    1. Create a restriction manifest based on the template created earlier:

    2. Create a constraint based on the constraint manifest:

      kubectl apply -f constraint.yaml
  3. Make sure that the constraint template and the constraint have been successfully created by running the command:

    kubectl get constraints,constrainttemplates

    Output should give you the similar information:

    NAME                                                              ENFORCEMENT-ACTION TOTAL-VIOLATIONSk8srequiredlabels.constraints.gatekeeper.sh/require-creator-label ...                ... NAME                                                              AGE...constrainttemplate.templates.gatekeeper.sh/k8srequiredlabels      ...
  4. Test the restriction by trying to create several namespaces:

    1. Create a manifest for the namespace:

    2. Try to create a namespace based on the manifest:

      kubectl apply -f example-allowed.yaml

      The operation should be completed successfully.

    3. Make sure that the namespace has been successfully created by running the command:

      kubectl get ns allowed-namespace

      Output should give you the similar information:

      NAME                STATUS   AGEallowed-namespace   Active   ...

Delete unused resources

  1. If the Kubernetes resources you created are no longer needed, delete them.

    kubectl delete ns allowed-namespacekubectl delete k8srequiredlabels.constraints.gatekeeper.sh/require-creator-labelkubectl delete constrainttemplate.templates.gatekeeper.sh/k8srequiredlabels
  2. A running cluster consumes computing resources. If you no longer need it: