Build Your Kubernetes Operator with the Right Tool
Tags: kubernetes, operators, operatorsdk, go
Published: 2020-11-24 12:11:01

<p>You want to build a Kubernetes Operator for your software. Which tool to choose from? Operator SDK with Helm, Ansible, or Go? Or maybe start from scratch with Python, Java, or any other programming language? In this blog post, I discuss different approaches to writing Kubernetes Operators and list each solution&#8217;s pros and cons. All that to help you decide which tool is the right one for you!</p>
<p>You can find the source code for this blog post <a href="https://github.com/leszko/build-your-operator">here</a>.</p>
![Build Your Operator with the Right Tool](https://dev-to-uploads.s3.amazonaws.com/i/lw97azwcoagx5el790xz.png)
<h2>Introduction</h2>
<p><a href="https://kubernetes.io/docs/concepts/extend-kubernetes/operator/">Kubernetes Operator</a> is an <strong>application </strong>that <strong>watches </strong>a custom Kubernetes <strong>resource </strong>and performs <strong>some operations</strong> upon its changes.</p>
<p>This definition is very generic because the operators themselves can do a great variety of things. To make it more digestible, let&#8217;s focus on one example that we will use throughout this blog post. This example will be a Hazelcast Operator used to create and scale a Hazelcast cluster. Let&#8217;s imagine that a user wants to manage the Hazelcast cluster via a custom Kubernetes resource <code>hazelcast.yaml</code>.</p>

```yaml
apiVersion: hazelcast.my.domain/v1
kind: Hazelcast
metadata:
  name: hazelcast-sample
spec:
  size: 1
```

<p>Upon applying this declarative configuration, a user wants to see a Hazelcast cluster with one Hazelcast member created.</p>
```
$ kubectl apply -f hazelcast.yaml
```
<p>Then, a user wants to be able to modify this resource configuration (i.e., change its size to 3), apply it again, and the Hazelcast cluster should resize automatically.</p>
![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/ap9afz9p0g4xx28538at.png)

<p>Hazelcast Operator is the <strong>application</strong> that watches the Hazelcast <strong>resource</strong> and interacts with Kubernetes API to <strong>create </strong>(or <strong>update</strong>) deployment with the given number of Hazelcast pod replicas.</p>
<p>This example is pretty simple, but in real life, a change in <code>hazelcast.yaml</code> could result in more complex operations. For example, cleaning data in the Hazelcast cluster, upgrading the Hazelcast version, sending metrics/logs to an external system, setting up WAN geo-replication, or creating some additional Kubernetes resources. There is no limit here; the point is that an operator observes your resource and performs any operation you want.</p>
<h2>Operator Similarities</h2>
<p>Since an operator is simply an <strong>application</strong>, technically, you can write it in <strong>any programming language or framework</strong>. What&#8217;s more, Kubernetes exposes a REST API, so you can really use any language to watch for Kubernetes events and to interact with the Kubernetes cluster. Nevertheless, no matter what implementation method you choose, operators have some similarities in how you build, install, and use them.</p>
<p>To create, install, and use an operator, you always have to:</p>
<ol>
<li>Implement the operator logic (in your preferred language/framework)</li>
<li>Dockerize your operator and push it to the Docker registry
<pre>$ docker build -t &lt;user&gt;/hazelcast-operator . &amp;&amp; docker push &lt;user&gt;/hazelcast-operator</pre>
</li>
<li>Create CRD (Custom Resource Definition), which defines your custom resource
<pre>$ kubectl apply -f hazelast.crd.yaml</pre>
</li>
<li>Create RBAC (Role and Role Binding) to allow an operator to interact with Kubernetes API
<pre>$ kubectl apply -f role.yaml
$ kubectl apply -f role_binding.yaml</pre>
</li>
<li>Deploy the operator into your Kubernetes cluster
<pre>$ kubectl apply -f operator.yaml</pre>
</li>
<li>Create your custom resource
<pre>$ kubectl apply -f hazelcast.yaml</pre>
</li>
</ol>
<p>Note that only the first point looks differently depending on the operator tool. All other steps are always exactly the same. That is why in the next sections we focus on implementing Hazelcast Operator using different techniques and for points 2-6, you can use the following source files: <a href="https://github.com/leszko/build-your-operator/blob/main/hazelcast.crd.yaml">hazelcast.crd.yaml</a>, <a href="https://github.com/leszko/build-your-operator/blob/main/role.yaml">role.yaml</a>, <a href="https://github.com/leszko/build-your-operator/blob/main/role_binding.yaml">role_binding.yaml</a>, <a href="https://github.com/leszko/build-your-operator/blob/main/operator.yaml">operator.yaml</a>, <a href="https://github.com/leszko/build-your-operator/blob/main/hazelcast.yaml">hazelcast.yaml</a>.</p>
<h2>Tools for building Operators</h2>
<p>Let&#8217;s start with the most popular tool for building operators, <a href="https://sdk.operatorframework.io/">Operator SDK</a>. It offers 3 approaches: Helm, Ansible, Go. Then, we&#8217;ll take a look into other operator frameworks, to close with the bare programming language implementation.</p>
<h3>Operator SDK: Helm</h3>
<p><a href="https://helm.sh/">Helm</a> is a package manager for Kubernetes. It allows you to create a set of templated Kubernetes configurations, package them into a Helm chart, and then render using parameters defined in <code>values.yaml</code>. Helm is very simple to use because creating a Helm chart requires no more knowledge than defining standard Kubernetes configuration files.</p>
<p>In our example, to create a <a href="https://github.com/leszko/build-your-operator/tree/main/operator-sdk-helm">Helm-based Hazelcast Operator</a>, we need first to <a href="https://github.com/leszko/build-your-operator/tree/main/operator-sdk-helm/chart">create the Hazelcast Helm Chart</a>.</p>
```
$ helm create chart
```
<p>Then, in <code>chart/templates</code> we can create <code>deployment.yaml</code>.</p>
```yaml
apiVersion: apps/v1
kind: Deployment
metadata:
  name: {{ include "hazelcast.fullname" . }}
spec:
  replicas: {{ .Values.size }}
  selector:
    matchLabels:
      app: hazelcast
  template:
    metadata:
      labels:
        app: hazelcast
    spec:
      containers:
        - name: hazelcast
          image: "hazelcast/hazelcast:4.1"
```
<p>Our only user parameter is the cluster size and we put it into <code>chart/values.yaml</code>.</p>
```yaml
size: 1
```
<p>Hazelcast Helm Chart is ready. Now we can generate an operator from it.</p>
```
$ operator-sdk init --plugins=helm
$ operator-sdk create api --group=hazelcast --version=v1 --helm-chart=./chart
```
<p>That&#8217;s it! The operator is ready. If you want to build, install, and use it, execute the common steps for all operators.</p>
```
$ docker build -t leszko/hazelcast-operator . &amp;&amp; docker push leszko/hazelcast-operator
$ make install                                 # create Hazelcast CRD
$ make deploy IMG=leszko/hazelcast-operator    # create operator RBAC and install operator deployment
$ kubectl apply -f config/samples/hazelcast_v1_hazelcast.yaml # create Hazelcast resource
```
<p>Note that you need to change <code>leszko</code> to your Docker Hub account name and make your Docker registry public.</p>
<p>A few <strong>comments about the &#8220;Operator SDK: Helm&#8221;</strong> approach:</p>
<ul>
<li>Operator implementation is <strong>declarative </strong>and therefore <strong>simple; it</strong> requires no more knowledge than the standard Kubernetes configurations</li>
<li>If you <strong>already have a Helm chart</strong> for your software, then creating an operator requires <strong>no work</strong> at all</li>
<li>Your operator functionality is <strong>limited to the features available in Helm</strong></li>
<li>All operator configuration files (hazelcast.crd.yaml, role.yaml, role_binding.yaml, operator.yaml hazelcast.yaml) are <strong>automatically generated</strong>, so you don&#8217;t need to maintain them separately</li>
</ul>
<h3>Operator SDK: Ansible</h3>

<p><a href="https://www.ansible.com/">Ansible</a> is a very powerful tool for IT automation. Its nature is declarative and, thanks to a number of plugins, you can write simple YAML files to perform complex DevOps tasks. Ansible has a plugin called <code>community.kubernetes.k8s</code> dedicated to interacting with Kubernetes API. What&#8217;s more, Operator SDK supports generating operators from Ansible roles.</p>
<p>To create an <a href="https://github.com/leszko/build-your-operator/tree/main/operator-sdk-ansible">Ansible-based Hazelcast Operator</a>, we need first to scaffold the Ansible operator project.</p>
```
$ operator-sdk init --plugins=ansible
$ operator-sdk create api --group hazelcast --version v1 --kind Hazelcast --generate-role
```
<p>Then, we can add the operator logic into <a href="https://github.com/leszko/build-your-operator/blob/main/operator-sdk-ansible/roles/hazelcast/tasks/main.yml">roles/hazelcast/tasks/main.yml</a>.</p>
```yaml
---
- name: start hazelcast
  community.kubernetes.k8s:
    definition:
      kind: Deployment
      apiVersion: apps/v1
      metadata:
        name: hazelcast
        namespace: '{{ ansible_operator_meta.namespace }}'
      spec:
        replicas: "{{size}}"
        selector:
          matchLabels:
            app: hazelcast
        template:
          metadata:
            labels:
              app: hazelcast
          spec:
            containers:
            - name: hazelcast
              image: "hazelcast/hazelcast:4.1"
```
<p>Finally, we can add operator default parameters into <a href="https://github.com/leszko/build-your-operator/blob/main/operator-sdk-ansible/roles/hazelcast/defaults/main.yml">roles/hazelcast/defaults/main.yml</a>.</p>
```yaml
---
size: 1
```
<p>Note that all the implementation logic looks very similar to the standard Kubernetes configuration and therefore, similar to the Helm-based operator. A significant difference is, however, that now all the configuration is interpreted by the <code>community.kubernetes.k8s</code> plugin, only later passed to Kubernetes API, while the Helm configuration was a direct Kubernetes configuration.</p>
<p>Steps to install, build, and use an Ansible-based operator are the same as for the Helm-based operator.</p>
```
$ docker build -t leszko/hazelcast-operator . &amp;&amp; docker push leszko/hazelcast-operator
$ make install                                 # create Hazelcast CRD
$ make deploy IMG=leszko/hazelcast-operator    # create operator RBAC and install operator deployment
$ kubectl apply -f config/samples/hazelcast_v1_hazelcast.yaml # create Hazelcast resource
```
<p>A few <strong>comments about the &#8220;Operator SDK: Ansible&#8221;</strong> approach:</p>
<ul>
<li>Ansible allows implementing operator in a <strong>declarative </strong>form which is concise and human-readable</li>
<li>Ansible operator is <strong>similar to the pure Kubernetes configuration</strong> but executed via the <code>community.kubernetes.k8s</code> plugin</li>
<li>Ansible is a very <strong>powerful tool</strong> and it lets you express almost any logic you may want</li>
<li>Similar to Helm-based operator, all configuration files (hazelcast.crd.yaml, role.yaml, role_binding.yaml, operator.yaml hazelcast.yaml) are <strong>automatically generated</strong>, so no need for any additional maintenance</li>
</ul>
<h3>Operator SDK: Go</h3>

<p><a href="https://golang.org/">Go</a> is a general-purpose programming language, so you can technically write any operator logic you could ever imagine. What&#8217;s more, the Kubernetes environment itself is written in Go, so the Kubernetes client library (interacting with Kubernetes API) is second to none. Operator SDK (with embedded <a href="https://github.com/kubernetes-sigs/kubebuilder">Kubebuilder</a>) supports implementing operators in Go, so you get a lot of scaffolding and code generation for free.</p>
<p>To create a <a href="https://github.com/leszko/build-your-operator/tree/main/operator-sdk-go">Go-based Hazelcast Operator</a>, we need first to execute a few commands to scaffold the project.</p>
```
$ operator-sdk init --repo=github.com/leszko/hazelcast-operator
$ operator-sdk create api --version v1 --group=hazelcast --kind Hazelcast --resource=true --controller=true
```
<p>Then, we are ready to implement the operator logic inside the function <code>Reconcile()</code> of the file <a href="https://github.com/leszko/build-your-operator/blob/main/operator-sdk-go/controllers/hazelcast_controller.go">controllers/hazelcast_controller.go</a>.</p>
```go
// +kubebuilder:rbac:groups=hazelcast.my.domain,resources=hazelcasts,verbs=get;list;watch;create;update;patch;delete
// +kubebuilder:rbac:groups=hazelcast.my.domain,resources=hazelcasts/status,verbs=get;update;patch
// +kubebuilder:rbac:groups=apps,resources=deployments,verbs=get;list;watch;create;update;patch;delete
// +kubebuilder:rbac:groups=core,resources=pods,verbs=get;list;watch

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

	// Fetch the Hazelcast instance
	hazelcast := &amp;hazelcastv1.Hazelcast{}
	err := r.Get(ctx, req.NamespacedName, hazelcast)
	if err != nil {
		if errors.IsNotFound(err) {
			log.Info("Hazelcast resource not found. Ignoring since object must be deleted")
			return ctrl.Result{}, nil
		}
		log.Error(err, "Failed to get Hazelcast")
		return ctrl.Result{}, err
	}

	// Check if the deployment already exists, if not create a new one
	found := &amp;appsv1.Deployment{}
	err = r.Get(ctx, types.NamespacedName{Name: hazelcast.Name, Namespace: hazelcast.Namespace}, found)
	if err != nil &amp;&amp; errors.IsNotFound(err) {
		// Define a new deployment
		dep := r.deploymentForHazelcast(hazelcast)
		log.Info("Creating a new Deployment", "Deployment.Namespace", dep.Namespace, "Deployment.Name", dep.Name)
		err = r.Create(ctx, dep)
		if err != nil {
			log.Error(err, "Failed to create new Deployment", "Deployment.Namespace", dep.Namespace, "Deployment.Name", dep.Name)
			return ctrl.Result{}, err
		}
		return ctrl.Result{Requeue: true}, nil
	} else if err != nil {
		log.Error(err, "Failed to get Deployment")
		return ctrl.Result{}, err
	}

	// Ensure the deployment size is the same as the spec
	size := hazelcast.Spec.Size
	if *found.Spec.Replicas != size {
		found.Spec.Replicas = &amp;size
		err = r.Update(ctx, found)
		if err != nil {
			log.Error(err, "Failed to update Deployment", "Deployment.Namespace", found.Namespace, "Deployment.Name", found.Name)
			return ctrl.Result{}, err
		}
		return ctrl.Result{Requeue: true}, nil
	}

	// Update the Hazelcast status with the pod names
	// List the pods for this hazelcast's deployment
	podList := &amp;corev1.PodList{}
	listOpts := []client.ListOption{
		client.InNamespace(hazelcast.Namespace),
		client.MatchingLabels(labelsForHazelcast(hazelcast.Name)),
	}
	if err = r.List(ctx, podList, listOpts...); err != nil {
		log.Error(err, "Failed to list pods", "Hazelcast.Namespace", hazelcast.Namespace, "Hazelcast.Name", hazelcast.Name)
		return ctrl.Result{}, err
	}
	podNames := getPodNames(podList.Items)

	// Update status.Nodes if needed
	if !reflect.DeepEqual(podNames, hazelcast.Status.Nodes) {
		hazelcast.Status.Nodes = podNames
		err := r.Status().Update(ctx, hazelcast)
		if err != nil {
			log.Error(err, "Failed to update Hazelcast status")
			return ctrl.Result{}, err
		}
	}

	return ctrl.Result{}, nil
}

// deploymentForHazelcast returns a hazelcast Deployment object
func (r *HazelcastReconciler) deploymentForHazelcast(m *hazelcastv1.Hazelcast) *appsv1.Deployment {
	ls := labelsForHazelcast(m.Name)
	replicas := m.Spec.Size

	dep := &amp;appsv1.Deployment{
		ObjectMeta: metav1.ObjectMeta{
			Name:      m.Name,
			Namespace: m.Namespace,
		},
		Spec: appsv1.DeploymentSpec{
			Replicas: &amp;replicas,
			Selector: &amp;metav1.LabelSelector{
				MatchLabels: ls,
			},
			Template: corev1.PodTemplateSpec{
				ObjectMeta: metav1.ObjectMeta{
					Labels: ls,
				},
				Spec: corev1.PodSpec{
					Containers: []corev1.Container{{
						Image: "hazelcast/hazelcast:4.1",
						Name:  "hazelcast",
					}},
				},
			},
		},
	}
	// Set Hazelcast instance as the owner and controller
	ctrl.SetControllerReference(m, dep, r.Scheme)
	return dep
}

// labelsForHazelcast returns the labels for selecting the resources
// belonging to the given hazelcast CR name.
func labelsForHazelcast(name string) map[string]string {
	return map[string]string{"app": "hazelcast", "hazelcast_cr": name}
}

// getPodNames returns the pod names of the array of pods passed in
func getPodNames(pods []corev1.Pod) []string {
	var podNames []string
	for _, pod := range pods {
		podNames = append(podNames, pod.Name)
	}
	return podNames
}</pre>
<p>We also need to add the size field to the Hazelcast resource structure in <a href="https://github.com/leszko/build-your-operator/blob/main/operator-sdk-go/api/v1/hazelcast_types.go">api/v1/hazelcast_types.go</a>.</p>
<pre>type HazelcastSpec struct {
	Size int32 `json:"size,omitempty"`
}
```
<p>You can already see that we had to write <strong>way more code</strong> and that this code is <strong>much more complex</strong> than the previous Operator SDK solutions. That&#8217;s all because we came from the <strong>declarative </strong>Kubernetes configurations to the <strong>imperative </strong>programming language. That means that now it&#8217;s not enough to change the size in the configuration, but we need to provide the code flow (with the proper error handling). That&#8217;s definitely more difficult! On the other hand, programming language gives you the flexibility to program anything you want. The declarative Kubernetes configuration no longer limits you and your operator can perform any logic you could ever imagine.</p>
<p>One thing to note is the list of comments above the <code>Reconcile()</code> function. They are used by Operator SDK to generate <code>role.yaml</code> for the operator.</p>
<p>Steps to install, build, and use a Go-based operator are the same as for any other Operator SDK operator.</p>
```
$ docker build -t leszko/hazelcast-operator . &amp;&amp; docker push leszko/hazelcast-operator
$ make install                                 # create Hazelcast CRD
$ make deploy IMG=leszko/hazelcast-operator    # create operator RBAC and install operator deployment
$ kubectl apply -f config/samples/hazelcast_v1_hazelcast.yaml # create Hazelcast resource
```
<p>A few <strong>comments about the &#8220;Operator SDK: Go&#8221;</strong> approach:</p>
<ul>
<li>You implement your operator in an <strong>imperative</strong> code, which requires more work and caution</li>
<li>Go language is <strong>well integrated with Kubernetes</strong></li>
<li>Writing an operator in the real programming language as Go means <strong>no limits on the functionality you want to implement</strong></li>
<li>Operator SDK helps to <strong>scaffold</strong> the Go operator project as well as <strong>generating boilerplate configuration files</strong> (hazelcast.crd.yaml, role.yaml, role_binding.yaml, operator.yaml, hazelcast.yaml)</li>
</ul>
<h3>Operator Framework: KOPF</h3>
<p>Operator SDK is the most popular tool for creating operators, but it&#8217;s not the only one. You can find some other interesting solutions for most programming languages, for example, <a href="https://github.com/java-operator-sdk/java-operator-sdk">Java Operator SDK</a> or <a href="https://kopf.readthedocs.io/">Kubernetes Operator Pythonic Framework (KOPF)</a>. The former one gained some traction because its implementation was started inside the Zalando company.</p>
<p>To start creating the <a href="https://github.com/leszko/build-your-operator/tree/main/kopf-python">KOPF-based Hazelcast Operator</a>, we first need to manually prepare all the boilerplate files: <a href="https://github.com/leszko/build-your-operator/blob/main/kopf-python/Dockerfile">Dockerfile</a> and <a href="https://github.com/leszko/build-your-operator/blob/main/kopf-python/hazelcast.crd.yaml">hazelcast.crd.yaml</a>, <a href="https://github.com/leszko/build-your-operator/blob/main/kopf-python/role.yaml">role.yaml</a>, <a href="https://github.com/leszko/build-your-operator/blob/main/kopf-python/role_binding.yaml">role_binding.yaml</a>, <a href="https://github.com/leszko/build-your-operator/blob/main/kopf-python/operator.yaml">operator.yaml</a>, and <a href="https://github.com/leszko/build-your-operator/blob/main/kopf-python/hazelcast.yaml">hazelcast.yaml</a>. Then, we&#8217;re ready to write the operator logic in the <a href="https://github.com/leszko/build-your-operator/blob/main/kopf-python/operator.py">operator.py</a> file.</p>
```python
import kopf
import pykube
import yaml

@kopf.on.create('hazelcast.my.domain', 'v1', 'hazelcasts')
def create_fn(spec, **kwargs):
    doc = create_deployment(spec)
    kopf.adopt(doc)

    api = pykube.HTTPClient(pykube.KubeConfig.from_env())
    deployment = pykube.Deployment(api, doc)
    deployment.create()

    api.session.close()

    return {'children': [deployment.metadata['uid']]}


@kopf.on.update('hazelcast.my.domain', 'v1', 'hazelcasts')
def update_fn(spec, **kwargs):
    api = pykube.HTTPClient(pykube.KubeConfig.from_env())
    deployment = pykube.Deployment.objects(api).get(name="hazelcast")
    deployment.replicas = spec.get('size', 1)
    deployment.update()
    
    api.session.close()

    return {'children': [deployment.metadata['uid']]}

def create_deployment(spec):
    return yaml.safe_load(f"""
        apiVersion: apps/v1
        kind: Deployment
        metadata:
          name: hazelcast
        spec:
          replicas: {spec.get('size', 1)}
          selector:
            matchLabels:
              app: hazelcast
          template:
            metadata:
              labels:
                app: hazelcast
            spec:
              containers:
                - name: hazelcast
                  image: "hazelcast/hazelcast:4.1"
    """)
```
<p>Python itself is quite a concise language and, thanks to using Python decorators, the code looks short, clean, and tidy. However, similar to Go-based implementation, you need to cover each operation (create and update) separately because we write the imperative code. One difference compared to Go is that the Python Kubernetes client is not as well integrated with Kubernetes as the Go Kubernetes client. Python uses YAML Kubernetes configurations and manipulates them, while Go operates on Kubernetes structures.</p>
<p>Steps to install, build, and use a KOPF-based operator are similar to what we saw before.</p>
```
$ docker build -t leszko/hazelcast-operator:kopf . &amp;&amp; docker push leszko/hazelcast-operator:kopf
$ kubectl apply -f hazelcast.crd.yaml # create Hazelcast CRD
$ kubectl apply -f role.yaml          # create operator RBAC
$ kubectl apply -f role_binding.yaml  # create operator RBAC
$ kubectl apply -f operator.yaml      # install operator
$ kubectl apply -f hazelcast.yaml     # create Hazelcast resource
```
<p>A few <strong>comments about the &#8220;Operator Framework&#8221;</strong> approach:</p>
<ul>
<li>Operator Frameworks for specific languages are <strong>less developed and popular</strong> than Operator SDK</li>
<li>While Operator SDK provides project <strong>scaffolding</strong> and <strong>boilerplate code generation,</strong> Operator Frameworks usually leave this work to a developer</li>
<li><strong>Kubernetes clients</strong> for Python, Java, or other languages are always <strong>slightly worse</strong> choice than the native Go Kubernetes client</li>
<li>Programming in any general-purpose language like Python or Java means that there is <strong>no limit on the functionary your operator provides</strong></li>
</ul>
<h3>Bare Programming Language: Java</h3>
<p>Operators are nothing more than dockerized applications, so technically you can write them in any programming language. Such a solution means, however, that you&#8217;re on your own. Nothing helps you in generating all the boilerplate code or configurations. On the other hand, you can choose the language you already use for other projects in your enterprise, decreasing the learning curve. A blog post <a href="https://www.instana.com/blog/writing-a-kubernetes-operator-in-java-part-1/">Writing a Kubernetes Operator in Java</a> describes how to implement an operator with Java, using Quarkus to increase the performance by building Docker native images. Let&#8217;s take a similar approach and create a <a href="https://github.com/leszko/build-your-operator/tree/main/java">Java-based Hazelcast Operator</a>.</p>
<p>We need first to manually prepare all the boilerplate files: <a href="https://github.com/leszko/build-your-operator/blob/main/java/hazelcast.crd.yaml">hazelcast.crd.yaml</a>, <a href="https://github.com/leszko/build-your-operator/blob/main/java/role.yaml">role.yaml</a>, <a href="https://github.com/leszko/build-your-operator/blob/main/java/role_binding.yaml">role_binding.yaml</a>, <a href="https://github.com/leszko/build-your-operator/blob/main/java/operator.yaml">operator.yaml</a>, and <a href="https://github.com/leszko/build-your-operator/blob/main/java/hazelcast.yaml">hazelcast.yaml</a>. We can then scaffold a Quarkus project using quarkus-maven-plugin or just clone the <a href="https://github.com/leszko/build-your-operator">source repository for this blog post</a>. Finally, we can implement the operator logic in a few classes.</p>
```java
public class ClientProvider {

    @Produces
    @Singleton
    @Named("namespace")
    private String findNamespace() throws IOException {
        return new String(Files.readAllBytes(Paths.get("/var/run/secrets/kubernetes.io/serviceaccount/namespace")));
    }

    @Produces
    @Singleton
    KubernetesClient newClient(@Named("namespace") String namespace) {
        return new DefaultKubernetesClient().inNamespace(namespace);
    }

    @Produces
    @Singleton
    NonNamespaceOperation&lt;HazelcastResource, HazelcastResourceList, HazelcastResourceDoneable, Resource&lt;HazelcastResource, HazelcastResourceDoneable&gt;&gt; makeCustomResourceClient(
            KubernetesClient defaultClient, @Named("namespace") String namespace) {

        KubernetesDeserializer.registerCustomKind("hazelcast.my.domain/v1", "Hazelcast", HazelcastResource.class);

        CustomResourceDefinition crd = defaultClient
                .customResourceDefinitions()
                .list()
                .getItems()
                .stream()
                .filter(d -&gt; "hazelcasts.hazelcast.my.domain".equals(d.getMetadata().getName()))
                .findAny()
                .orElseThrow(
                        () -&gt; new RuntimeException(
                                "Deployment error: Custom resource definition \"hazelcasts.hazelcast.my.domain\" not found."));

        return defaultClient
                .customResources(crd, HazelcastResource.class, HazelcastResourceList.class, HazelcastResourceDoneable.class)
                .inNamespace(namespace);
    }
}
    
@ApplicationScoped
public class DeploymentInstaller {

    @Inject
    private KubernetesClient client;

    @Inject
    private HazelcastResourceCache cache;

    void onStartup(@Observes StartupEvent _ev) {
        new Thread(this::runWatch).start();
    }

    private void runWatch() {
        cache.listThenWatch(this::handleEvent);
    }

    private void handleEvent(Watcher.Action action, String uid) {
        try {
            HazelcastResource resource = cache.get(uid);
            if (resource == null) {
                return;
            }

            Predicate ownerRefMatches = deployments -&gt; deployments.getMetadata().getOwnerReferences().stream()
                    .anyMatch(ownerReference -&gt; ownerReference.getUid().equals(uid));


            List hazelcastDeployments = client.apps().deployments().list().getItems().stream()
                    .filter(ownerRefMatches)
                    .collect(toList());

            if (hazelcastDeployments.isEmpty()) {
                client.apps().deployments().create(newDeployment(resource));
            } else {
                for (Deployment deployment : hazelcastDeployments) {
                    setSize(deployment, resource);
                    client.apps().deployments().createOrReplace(deployment);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            System.exit(-1);
        }
    }

    private Deployment newDeployment(HazelcastResource resource) {
        Deployment deployment = client.apps().deployments().load(getClass().getResourceAsStream("/deployment.yaml")).get();
        setSize(deployment, resource);
        deployment.getMetadata().getOwnerReferences().get(0).setUid(resource.getMetadata().getUid());
        deployment.getMetadata().getOwnerReferences().get(0).setName(resource.getMetadata().getName());
        return deployment;
    }

    private void setSize(Deployment deployment, HazelcastResource resource) {
        deployment.getSpec().setReplicas(resource.getSpec().getSize());
    }
}
    
@ApplicationScoped
public class HazelcastResourceCache {

    private final Map&lt;String, HazelcastResource&gt; cache = new ConcurrentHashMap&lt;&gt;();

    @Inject
    private NonNamespaceOperation&lt;HazelcastResource, HazelcastResourceList, HazelcastResourceDoneable, Resource&lt;HazelcastResource, HazelcastResourceDoneable&gt;&gt; crClient;

    private Executor executor = Executors.newSingleThreadExecutor();

    public HazelcastResource get(String uid) {
        return cache.get(uid);
    }

    public void listThenWatch(BiConsumer&lt;Watcher.Action, String&gt; callback) {

        try {
            // list
            crClient
                    .list()
                    .getItems()
                    .forEach(resource -&gt; {
                                cache.put(resource.getMetadata().getUid(), resource);
                                String uid = resource.getMetadata().getUid();
                                executor.execute(() -&gt; callback.accept(Watcher.Action.ADDED, uid));
                            }
                    );

            // watch
            crClient.watch(new Watcher() {
                @Override
                public void eventReceived(Action action, HazelcastResource resource) {
                    try {
                        String uid = resource.getMetadata().getUid();
                        if (cache.containsKey(uid)) {
                            int knownResourceVersion = Integer.parseInt(cache.get(uid).getMetadata().getResourceVersion());
                            int receivedResourceVersion = Integer.parseInt(resource.getMetadata().getResourceVersion());
                            if (knownResourceVersion &gt; receivedResourceVersion) {
                                return;
                            }
                        }
                        System.out.println("received " + action + " for resource " + resource);
                        if (action == Action.ADDED || action == Action.MODIFIED) {
                            cache.put(uid, resource);
                        } else if (action == Action.DELETED) {
                            cache.remove(uid);
                        } else {
                            System.err.println("Received unexpected " + action + " event for " + resource);
                            System.exit(-1);
                        }
                        executor.execute(() -&gt; callback.accept(action, uid));
                    } catch (Exception e) {
                        e.printStackTrace();
                        System.exit(-1);
                    }
                }

                @Override
                public void onClose(KubernetesClientException cause) {
                    cause.printStackTrace();
                    System.exit(-1);
                }
            });
        } catch (Exception e) {
            e.printStackTrace();
            System.exit(-1);
        }
    }
}
```
<p>Additionally, we need to add the Kubernetes configuration file <code>src/main/resources/deployment.yaml</code>, used in the Java code.</p>
```yaml
apiVersion: apps/v1
kind: Deployment
metadata:
  name: hazelcast
  ownerReferences:
    - apiVersion: apps/v1
      kind: Hazelcast
      name: placeholder
      uid: placeholder
spec:
  replicas: 1
  selector:
    matchLabels:
      app: hazelcast
  template:
    metadata:
      labels:
        app: hazelcast
    spec:
      containers:
        - name: hazelcast
          image: "hazelcast/hazelcast:4.1"
```
<p>Apart from the code above, we need to add additional Java boilerplate classes: <a href="https://github.com/leszko/build-your-operator/blob/main/java/src/main/java/com/hazelcast/operator/cr/HazelcastResource.java">HazelcastResource</a>, <a href="https://github.com/leszko/build-your-operator/blob/main/java/src/main/java/com/hazelcast/operator/cr/HazelcastResourceDoneable.java">HazelcastResourceDoneable</a>, <a href="https://github.com/leszko/build-your-operator/blob/main/java/src/main/java/com/hazelcast/operator/cr/HazelcastResourceList.java">HazelcastResourceList</a>, <a href="https://github.com/leszko/build-your-operator/blob/main/java/src/main/java/com/hazelcast/operator/cr/HazelcastResourceSpec.java">HazelcastResourceSpec</a>. Yes&#8230; the combination of using Java and not using any Operator Framework must result in a lot of code. A lot of code to write and a lot of code to maintain. Java is verbose; Java Kubernetes client is verbose. That&#8217;s it. For details of the code above, I recommend reading <a href="https://www.instana.com/blog/writing-a-kubernetes-operator-in-java-part-1/">Writing a Kubernetes Operator in Java</a>. You can also check there the tweaks you need to make to build the Docker native image.</p>
<p>We can build the application in two ways: Java Docker image or Docker native image. The second approach is better for the performance but requires a few tweaks in code, so for the purpose of this blog post, let&#8217;s just build a standard Docker image (and then install and use it),</p>
```
$ mvn package
$ docker build -f src/main/docker/Dockerfile.jvm -t leszko/hazelcast-operator:java . &amp;&amp; docker push leszko/hazelcast-operator:java
$ kubectl apply -f hazelcast.crd.yaml # create Hazelcast CRD
$ kubectl apply -f role.yaml          # create operator RBAC
$ kubectl apply -f role_binding.yaml  # create operator RBAC
$ kubectl apply -f operator.yaml      # install operator
$ kubectl apply -f hazelcast.yaml     # create Hazelcast resource
```
<p>A few <strong>comments about the &#8220;Bare Programming Language&#8221;</strong> approach:</p>
<ul>
<li>Creating an operator from scratch means <strong>writing more code</strong></li>
<li>There is<strong> no limit on the logic</strong> you want to deliver</li>
<li>Before starting to write an operator in your preferred language, you can check if it provides a <strong>good and mature Kubernetes client library</strong></li>
<li>The only good reason to write an operator from scratch is using <strong>a single programming language</strong> inside your project/organization/enterprise</li>
</ul>
<h2>Summary</h2>
<p>You can look at the code snippets above and decide which operator implementation is the right one for you. However, that&#8217;s just a part of the story. Let me give you an example. I&#8217;m a Java developer, so for me using pure Java is the simplest approach. Still, I would never choose Java for writing an operator. Why? Most developers do not write operators in Java. So, I&#8217;d be alone in it! Alone with bugs, alone with new features, alone with my questions on StackOverflow. And programming is a collaborative work!</p>
<p>Then, what operator tool do others use? Let&#8217;s look at the data from <a href="https://operatorhub.io/">OperatorHub.io</a>.</p>

![OperatorHub Stats](https://dev-to-uploads.s3.amazonaws.com/i/7gbq7zuzxnmeo7shg4gn.png)

<p>Go-based operators are by far the most popular. You may find the data slightly biased because the operators published at OperatorHub are only those operators that are built and distributed for others, so you won&#8217;t find any internal operators there. But still, if you decide to develop your operator in Go, you&#8217;re in good company!</p>
<p>So, which operator implementation is the right one for you? The choice is yours, but let me give you some hints.</p>
<ul>
<li><strong>Hint 1</strong>: If you <strong>already have a Helm chart</strong> for your software and you don&#8217;t need any complex <a href="https://operatorframework.io/operator-capabilities/">capability levels</a> =&gt; Operator SDK: Helm</li>
<li><strong>Hint 2</strong>: If you want to <strong>create your operator quickly</strong> and you don&#8217;t need any complex <a href="https://operatorframework.io/operator-capabilities/">capability levels</a> =&gt; Operator SDK: Helm</li>
<li><strong>Hint 3: </strong>If you want <strong>complex features</strong> or/and be flexible about any future implementations =&gt; Operator SDK: Go</li>
<li><strong>Hint 4</strong>: If you want to keep a <strong>single programming language in your organization</strong>
<ul>
<li>If a popular Operator Framework exists for your language or/and you want to contribute to it =&gt; Operator Framework</li>
<li>If no popular Operator Framework exists for your programming language =&gt; Bare Programming Language</li>
</ul>
</li>
<li><strong>Hint 5</strong>: If <strong>none of the above</strong> =&gt; Operator SDK: Go</li>
</ul>