Convert Figma logo to code with AI

kubernetes-sigs logokubebuilder

Kubebuilder - SDK for building Kubernetes APIs using CRDs

7,734
1,429
7,734
50

Top Related Projects

SDK for building Kubernetes applications. Provides high level APIs, useful abstractions, and project scaffolding.

Repository for sample controller. Complements sample-apiserver

Repo for the controller-runtime subproject of kubebuilder (sig-apimachinery)

10,890

Customization of kubernetes YAML configurations

26,764

The Kubernetes Package Manager

Quick Overview

Kubebuilder is an SDK for building Kubernetes APIs using Custom Resource Definitions (CRDs). It provides a framework to develop Kubernetes native applications and extensions, simplifying the process of creating custom controllers and operators.

Pros

  • Streamlines the development of Kubernetes operators and custom controllers
  • Provides scaffolding tools to quickly generate project structure and boilerplate code
  • Integrates well with existing Kubernetes tooling and practices
  • Offers built-in testing utilities for controller logic

Cons

  • Steep learning curve for developers new to Kubernetes concepts
  • Limited flexibility in some aspects of project structure and code organization
  • May generate more code than necessary for simple use cases
  • Requires periodic updates to keep up with Kubernetes API changes

Code Examples

  1. Creating a new API:
kubebuilder create api --group webapp --version v1 --kind Guestbook

This command creates a new API with the specified group, version, and kind.

  1. Implementing reconciliation logic:
func (r *GuestbookReconciler) Reconcile(ctx context.Context, req ctrl.Request) (ctrl.Result, error) {
    log := r.Log.WithValues("guestbook", req.NamespacedName)

    var guestbook webappv1.Guestbook
    if err := r.Get(ctx, req.NamespacedName, &guestbook); err != nil {
        log.Error(err, "unable to fetch Guestbook")
        return ctrl.Result{}, client.IgnoreNotFound(err)
    }

    // Add custom reconciliation logic here

    return ctrl.Result{}, nil
}

This example shows the basic structure of a reconciliation function for a custom resource.

  1. Adding RBAC permissions:
//+kubebuilder:rbac:groups=webapp.my.domain,resources=guestbooks,verbs=get;list;watch;create;update;patch;delete
//+kubebuilder:rbac:groups=webapp.my.domain,resources=guestbooks/status,verbs=get;update;patch

These annotations generate RBAC rules for the controller to interact with Guestbook resources.

Getting Started

  1. Install Kubebuilder:

    curl -L -o kubebuilder https://go.kubebuilder.io/dl/latest/$(go env GOOS)/$(go env GOARCH)
    chmod +x kubebuilder && mv kubebuilder /usr/local/bin/
    
  2. Create a new project:

    mkdir myproject && cd myproject
    kubebuilder init --domain my.domain
    
  3. Create an API:

    kubebuilder create api --group webapp --version v1 --kind Guestbook
    
  4. Implement controller logic in controllers/guestbook_controller.go

  5. Generate manifests and deploy:

    make manifests
    make install
    make run
    

Competitor Comparisons

SDK for building Kubernetes applications. Provides high level APIs, useful abstractions, and project scaffolding.

Pros of Operator SDK

  • Provides a higher level of abstraction for creating operators
  • Offers built-in scaffolding for Ansible and Helm-based operators
  • Includes additional tools for testing and validating operators

Cons of Operator SDK

  • Steeper learning curve due to more complex architecture
  • Less flexibility in customizing the operator structure
  • Potentially more dependencies and overhead

Code Comparison

Kubebuilder:

type MyCustomResource struct {
    metav1.TypeMeta   `json:",inline"`
    metav1.ObjectMeta `json:"metadata,omitempty"`
    Spec   MyCustomResourceSpec   `json:"spec,omitempty"`
    Status MyCustomResourceStatus `json:"status,omitempty"`
}

Operator SDK:

type MyCustomResource struct {
    metav1.TypeMeta   `json:",inline"`
    metav1.ObjectMeta `json:"metadata,omitempty"`
    Spec   MyCustomResourceSpec   `json:"spec"`
    Status MyCustomResourceStatus `json:"status,omitempty"`
}

Both Kubebuilder and Operator SDK are popular frameworks for building Kubernetes operators. Kubebuilder is more lightweight and focuses on Go-based operators, while Operator SDK offers a broader range of options including Ansible and Helm-based operators. The code structure for defining custom resources is similar in both frameworks, with minor differences in field tags. Ultimately, the choice between the two depends on the specific requirements of your project and your preferred development approach.

Repository for sample controller. Complements sample-apiserver

Pros of sample-controller

  • Simpler and more lightweight, ideal for learning basic controller concepts
  • Provides a bare-bones example without additional abstractions
  • Closer to the underlying Kubernetes API, offering more direct control

Cons of sample-controller

  • Requires more boilerplate code for complex controllers
  • Lacks built-in scaffolding and code generation tools
  • May require more manual updates as Kubernetes APIs evolve

Code Comparison

sample-controller:

func (c *Controller) syncHandler(key string) error {
    namespace, name, err := cache.SplitMetaNamespaceKey(key)
    if err != nil {
        return err
    }
    foo, err := c.foosLister.Foos(namespace).Get(name)
    if err != nil {
        if errors.IsNotFound(err) {
            return nil
        }
        return err
    }
    // ... (controller logic)
}

Kubebuilder:

func (r *FooReconciler) Reconcile(req ctrl.Request) (ctrl.Result, error) {
    ctx := context.Background()
    log := r.Log.WithValues("foo", req.NamespacedName)

    var foo myappv1.Foo
    if err := r.Get(ctx, req.NamespacedName, &foo); err != nil {
        log.Error(err, "unable to fetch Foo")
        return ctrl.Result{}, client.IgnoreNotFound(err)
    }
    // ... (reconciler logic)
}

Repo for the controller-runtime subproject of kubebuilder (sig-apimachinery)

Pros of controller-runtime

  • More flexible and customizable for advanced use cases
  • Provides lower-level building blocks for creating controllers
  • Better suited for complex operator development

Cons of controller-runtime

  • Steeper learning curve for beginners
  • Requires more boilerplate code and manual setup
  • Less opinionated, which can lead to inconsistent implementations

Code Comparison

Kubebuilder:

type MyReconciler struct {
    client.Client
    Log    logr.Logger
    Scheme *runtime.Scheme
}

func (r *MyReconciler) Reconcile(req ctrl.Request) (ctrl.Result, error) {
    // Reconciliation logic here
}

controller-runtime:

mgr, err := ctrl.NewManager(ctrl.GetConfigOrDie(), ctrl.Options{})
if err != nil {
    // Handle error
}

err = (&MyReconciler{}).SetupWithManager(mgr)
if err != nil {
    // Handle error
}

Summary

Kubebuilder is built on top of controller-runtime and provides a higher-level abstraction for creating Kubernetes operators. It offers scaffolding, code generation, and a more opinionated approach, making it easier for beginners to get started. controller-runtime, on the other hand, provides the core building blocks for creating controllers and is more flexible for advanced use cases. While Kubebuilder is great for quick development and standardization, controller-runtime offers more control and customization options for complex operator development.

10,890

Customization of kubernetes YAML configurations

Pros of Kustomize

  • Focused on customizing Kubernetes manifests without modifying original YAML files
  • Lightweight and easy to integrate into existing workflows
  • Supports overlays for managing environment-specific configurations

Cons of Kustomize

  • Limited to manifest customization, not a full-fledged operator development framework
  • Lacks scaffolding and code generation capabilities for complex custom resources
  • May require additional tools for comprehensive Kubernetes application development

Code Comparison

Kustomize example:

apiVersion: kustomize.config.k8s.io/v1beta1
kind: Kustomization
resources:
- deployment.yaml
- service.yaml

Kubebuilder example:

func (r *MyAppReconciler) Reconcile(ctx context.Context, req ctrl.Request) (ctrl.Result, error) {
    // Reconciliation logic here
    return ctrl.Result{}, nil
}

Summary

Kustomize is a specialized tool for customizing Kubernetes manifests, offering a lightweight approach to configuration management. It excels in simplifying manifest modifications across environments.

Kubebuilder, on the other hand, is a comprehensive framework for building Kubernetes operators and custom controllers. It provides scaffolding, code generation, and testing utilities for developing complex Kubernetes-native applications.

While Kustomize focuses on manifest customization, Kubebuilder offers a more extensive set of tools for building and managing Kubernetes operators and custom resources.

26,764

The Kubernetes Package Manager

Pros of Helm

  • Simpler templating and package management for Kubernetes resources
  • Easier rollbacks and version control of deployments
  • Broader ecosystem with a large repository of pre-built charts

Cons of Helm

  • Less granular control over custom resource definitions (CRDs)
  • Steeper learning curve for complex applications
  • Limited support for advanced Kubernetes features and operators

Code Comparison

Helm chart example:

apiVersion: v1
kind: Deployment
metadata:
  name: {{ .Release.Name }}-myapp
spec:
  replicas: {{ .Values.replicaCount }}

Kubebuilder example:

type MyApp struct {
    metav1.TypeMeta   `json:",inline"`
    metav1.ObjectMeta `json:"metadata,omitempty"`
    Spec              MyAppSpec   `json:"spec,omitempty"`
    Status            MyAppStatus `json:"status,omitempty"`
}

Helm focuses on templating and packaging Kubernetes manifests, while Kubebuilder provides a framework for building custom controllers and operators. Helm is better suited for deploying applications with standard Kubernetes resources, whereas Kubebuilder excels in creating complex, custom resources and controllers for advanced use cases.

Helm's templating approach makes it easier to manage and deploy applications across different environments, but it may lack the flexibility needed for highly customized Kubernetes extensions. Kubebuilder, on the other hand, offers more control over custom resources and controllers but requires more in-depth knowledge of Kubernetes internals and Go programming.

Convert Figma logo designs to code with AI

Visual Copilot

Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.

Try Visual Copilot

README

Lint Unit tests Go Report Card Coverage Status Latest release

Kubebuilder

Kubebuilder is a framework for building Kubernetes APIs using custom resource definitions (CRDs).

Similar to web development frameworks such as Ruby on Rails and SpringBoot, Kubebuilder increases velocity and reduces the complexity managed by developers for rapidly building and publishing Kubernetes APIs in Go. It builds on top of the canonical techniques used to build the core Kubernetes APIs to provide simple abstractions that reduce boilerplate and toil.

Kubebuilder does not exist as an example to copy-paste, but instead provides powerful libraries and tools to simplify building and publishing Kubernetes APIs from scratch. It provides a plugin architecture allowing users to take advantage of optional helpers and features. To learn more about this see the Plugin section.

Kubebuilder is developed on top of the controller-runtime and controller-tools libraries.

Kubebuilder is also a library

Kubebuilder is extensible and can be used as a library in other projects. Operator-SDK is a good example of a project that uses Kubebuilder as a library. Operator-SDK uses the plugin feature to include non-Go operators e.g. operator-sdk's Ansible and Helm-based language Operators.

To learn more see how to create your own plugins.

Installation

It is strongly recommended that you use a released version. Release binaries are available on the releases page. Follow the instructions to install Kubebuilder.

Getting Started

See the Getting Started documentation.

Quick Start

Also, ensure that you check out the Deploy Image Plugin. This plugin allows users to scaffold API/Controllers to deploy and manage an Operand (image) on the cluster following the guidelines and best practices. It abstracts the complexities of achieving this goal while allowing users to customize the generated code.

Documentation

Check out the Kubebuilder book.

Resources

Motivation

Building Kubernetes tools and APIs involves making a lot of decisions and writing a lot of boilerplate.

In order to facilitate easily building Kubernetes APIs and tools using the canonical approach, this framework provides a collection of Kubernetes development tools to minimize toil.

Kubebuilder attempts to facilitate the following developer workflow for building APIs

  1. Create a new project directory
  2. Create one or more resource APIs as CRDs and then add fields to the resources
  3. Implement reconcile loops in controllers and watch additional resources
  4. Test by running against a cluster (self-installs CRDs and starts controllers automatically)
  5. Update bootstrapped integration tests to test new fields and business logic
  6. Build and publish a container from the provided Dockerfile

Scope

Building APIs using CRDs, Controllers and Admission Webhooks.

Philosophy

See DESIGN.md for the guiding principles of the various Kubebuilder projects.

TL;DR:

Provide clean library abstractions with clear and well exampled godocs.

  • Prefer using go interfaces and libraries over relying on code generation
  • Prefer using code generation over 1 time init of stubs
  • Prefer 1 time init of stubs over forked and modified boilerplate
  • Never fork and modify boilerplate

Techniques

  • Provide higher level libraries on top of low level client libraries
    • Protect developers from breaking changes in low level libraries
    • Start minimal and provide progressive discovery of functionality
    • Provide sane defaults and allow users to override when they exist
  • Provide code generators to maintain common boilerplate that can't be addressed by interfaces
    • Driven off of // + comments
  • Provide bootstrapping commands to initialize new packages

Versioning and Releasing

See VERSIONING.md.

Troubleshooting

  • Bugs and Feature Requests:

    If you have what looks like a bug, or you would like to make a feature request, please use the Github issue tracking system. Before you file an issue, please search existing issues to see if your issue is already covered.

  • Slack

    For realtime discussion, you can join the #kubebuilder slack channel. Slack requires registration, but the Kubernetes team is open invitation to anyone to register here. Feel free to come and ask any questions.

Contributing

Contributions are greatly appreciated. The maintainers actively manage the issues list, and try to highlight issues suitable for newcomers. The project follows the typical GitHub pull request model. See CONTRIBUTING.md for more details. Before starting any work, please either comment on an existing issue, or file a new one.

Operating Systems Supported

Currently, Kubebuilder officially supports macOS and Linux platforms. If you are using a Windows OS, you may encounter issues. Contributions towards supporting Windows are welcome.

Versions Compatibility and Supportability

Projects created by Kubebuilder contain a Makefile that installs tools at versions defined during project creation. The main tools included are:

Additionally, these projects include a go.mod file specifying dependency versions. Kubebuilder relies on controller-runtime and its Go and Kubernetes dependencies. Therefore, the versions defined in the Makefile and go.mod files are the ones that have been tested, supported, and recommended.

Each minor version of Kubebuilder is tested with a specific minor version of client-go. While a Kubebuilder minor version may be compatible with other client-go minor versions, or other tools this compatibility is not guaranteed, supported, or tested.

The minimum Go version required by Kubebuilder is determined by the highest minimum Go version required by its dependencies. This is usually aligned with the minimum Go version required by the corresponding k8s.io/* dependencies.

Compatible k8s.io/* versions, client-go versions, and minimum Go versions can be found in the go.mod file scaffolded for each project for each tag release.

Example: For the 4.1.1 release, the minimum Go version compatibility is 1.22. You can refer to the samples in the testdata directory of the tag released v4.1.1, such as the go.mod file for project-v4. You can also check the tools versions supported and tested for this release by examining the Makefile.

Community Meetings

The following meetings happen biweekly:

  • Kubebuilder Meeting

You are more than welcome to attend. For further info join to kubebuilder@googlegroups.com. Every month, our team meets on the first Thursday at 11:00 PT (Pacific Time) to discuss our progress and plan for the upcoming weeks.