3

I am trying my hands on creating my own kubernetes operator by following this link. In the Reconcile function, I need to create multiple Deployments and each will vary in some attributes (like name for e.g.) and the configuration is huge. Instead of creating the deployment by using appsv1.Deployment and creating each attributes within it (like below code), is there a way wherein I can provide a yaml template file and read this file to obtain the appsv1.Deployment object?

    dep := &appsv1.Deployment{
        ObjectMeta: metav1.ObjectMeta{
            Name:      customName,
            Namespace: m.Namespace,
        },
        Spec: appsv1.DeploymentSpec{
            Strategy: appsv1.DeploymentStrategy{
                Type: "RollingUpdate",
            },
        ... and so on

Instead of above, can something like below possible with some handy util functions?

dep := utils.parseYaml(deploymentYamlFile)
Jonathan Hall
  • 75,165
  • 16
  • 143
  • 189
Vishal
  • 549
  • 3
  • 13

1 Answers1

2

Yes, you can have your Deployment in a yaml file and read it in code.

Given this file structure:

example.go
manifests/deployment.yaml

You would have something like this in example.go:

import (
    "io/ioutil"

    appsv1 "k8s.io/api/apps/v1"
    "sigs.k8s.io/yaml"
)

func example() {
    var bs []byte
    {
        bs, err = ioutil.ReadFile("manifests/deployment.yaml")
        if err != nil {
            // handle err
        }
    }

    var deployment appsv1.Deployment
    err = yaml.Unmarshal(bs, &deployment)
    if err != nil {
        // handle err
    }

    // now you have your deployment load into `deployment` var
}
Nikola Prokopić
  • 3,246
  • 3
  • 17
  • 20
  • Thank you so much for the quick response. I will give this a try now :) – Vishal Jul 05 '21 at 13:11
  • 1
    Is it possible to use any existing templating/overlay tools such as helm or kustomize within the operator? In this way, I can avoid writing the templating/overlay logic to add my custom values to the deployment manifest. – dinup24 Jun 07 '22 at 07:56