Git Product home page Git Product logo

kubernetes-cel-validator's Introduction

Kubernetes CEL Validator

Description

This is a library to validate Kubernetes cluster resources against a set of rules defined using the CEL language.

The CEL used uses both CEL community libraries and Kubernetes CEL libraries.

Please read the CEL Introduction at https://kubernetes.io/docs/reference/using-api/cel/ to know about working with CEL.

Go Build and Test

Usage

This is a library that can be used in your own Go code. You can use it in your own code by importing it:

package testvalidate

import (
	celvalidator "github.com/accuknox/kubernetes-cel-validator/resource-cel-validator/pkg"
	celvalidatortypes "github.com/accuknox/kubernetes-cel-validator/resource-cel-validator/pkg/types"
	metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
	"k8s.io/apimachinery/pkg/runtime/schema"
	"k8s.io/client-go/rest"
)

func ValidateResource(config *rest.Config) (bool, []celvalidatortypes.ValidationFailure, celvalidatortypes.ValidationFailure, error) {
	kubernetesResourcePrecondition := celvalidatortypes.KubernetesResourcePrecondition{
		Name: "test-precondition",
		MatchResources: &celvalidatortypes.MatchResources{
			NamespaceSelector: &metav1.LabelSelector{
				MatchLabels: map[string]string{
					"test": "test",
				},
			},
			ObjectSelector: &metav1.LabelSelector{
				MatchLabels: map[string]string{
					"test": "test",
				},
			},
			ResourceRules: []schema.GroupVersionResource{
				{
					Group:    "apps",
					Version:  "v1",
					Resource: "deployments",
				},
			},
			SelectionPreconditions: []celvalidatortypes.Validation{
				{
					Key:               "test-label-using-cel",
					Expression:        "object.metadata.labels.foo == 'bar'",
					MessageExpression: "resource.metadata.name + ' does not have label foo=bar'",
				},
			},
		},
		Validations: []celvalidatortypes.Validation{
			{
				Key:               "test-replicas",
				Expression:        "object.spec.replicas > 1",
				MessageExpression: "resource.metadata.name + ' has more than 1 replica'",
			},
		},
	}

	validationResult, selectionPreconditionValidationFailures, validationFailure, err := celvalidator.GetKubernetesResourcePreconditionResult(&kubernetesResourcePrecondition, config)
	return validationResult, selectionPreconditionValidationFailures, validationFailure, err
}

The method celvalidator.GetKubernetesResourcePreconditionResult(..) returns:

  1. A boolean value indicating the result of the validation.
  2. A list of celvalidatortypes.ValidationFailure objects which contain details of object that failed the **SelectionPreconditions**.
  3. A celvalidatortypes.ValidationFailure object which contains details of the object that failed the **Validations**.
  4. An error that might be encountered during validation phase, resource selection phase or during the creation of the Kubernetes client.

Field Specification

It is really common to use YAML to specify the rules and then unmarshal it into the celvalidatortypes.KubernetesResourcePrecondition object. The following is an example of the YAML specification:

name: replicas-precondition # Mandatory, name of the precondition
matchResources:             # Mandatory, resource selection criteria
  namespaceSelector:        # Optional, namespace selection criteria
    matchExpressions:       # Optional, namespace selection criteria
      - key: hoo
        operator: DoesNotExist
    matchLabels:            # Optional, namespace selection criteria
      kubernetes.io/metadata.name: validation-test-ns
  objectSelector:           # Optional, object selection criteria
    matchExpressions:       # Optional, object selection criteria
      - key: hoo
        operator: DoesNotExist
    matchLabels:            # Optional, object selection criteria
      app: nginx
  resourceRules:            # Mandatory, resource selection criteria, at least one resource rule is required
    - Group: apps
      Version: v1
      Resource: deployments
  selectionPreconditions:   # Optional, selection preconditions
    - key: "nginx-name"     # Optional, key of the precondition
      messageExpression: "'resource: ' + object.metadata.name + ' is not nginx'" # Optional, message to be displayed when the precondition fails
      expression: "object.metadata.name == 'nginx'"                              # Mandatory, CEL expression to be evaluated
validations:                                # Mandatory, validations, at least one validation is required
  - expression: "object.spec.replicas == 1" # Mandatory, CEL expression to be evaluated
    key: "single-replica"                   # Optional, key of the validation
    messageExpression: "'resource: ' + object.metadata.name + ' does not have 1 replica, it has ' + string(object.spec.replicas)" 
                                            # ⬆ Optional, message to be displayed when the validation fails

Contributing

  1. Fork it
  2. Create your feature branch (git checkout -b my-new-feature)
  3. Commit your changes (git commit -s -m'Add some feature') (Commits need to be signed)
  4. Push to the branch (git push origin my-new-feature)
  5. Create new Pull Request

kubernetes-cel-validator's People

Contributors

vyom-yadav avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar

kubernetes-cel-validator's Issues

Interest in tagged versioning

Love what this library entails and want to attribute my use of it in any projects to the original source as opposed to forking or other methods.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.