Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Kubernetes operator create Deployment using yaml template

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)
like image 284
Vishal Avatar asked Dec 09 '25 18:12

Vishal


1 Answers

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
}
like image 163
Nikola Prokopić Avatar answered Dec 12 '25 16:12

Nikola Prokopić



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!