Skip to content

Unmarshal Kubernetes objects from templates

Hossein Pursultani requested to merge 19-unmarshal-objects into main

This MR is based on the template engine in !28 (merged). Do not merge it before !28 (merged) is merged.

What does this MR do?

This change introduces TemplateInventory. An inventory for Kubernetes objects that are deserialized from rendering YAML templates.

The TemplateInventory renders a named group of templates (using the Template engine). It accepts an optional Decoder for deserializing objects. When decoder is not provided it uses the default UniversalDecoder.

How to test

  1. Create the template directory and sample YAML template files for Kubernetes resource:

    mkdir -p assets/templates/test-2/
    cat assets/templates/test-2/secret-1.yaml <<EOF
    apiVersion: v1
    kind: Secret
    metadata:
      name: {{ .Name }}-secret-1
      namespace: {{ .Namespace }}
    type: Opaque
    data:
      hello: d29ybGQK
    EOF
  2. The following code snippet prints our Kubernetes resource details:

    package main
    
    import (
        "context"
        "fmt"
    
        corev1 "k8s.io/api/core/v1"
        metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
    
        "gitlab.com/gitlab-org/cloud-native/operator/pkg/framework/inventory"
    )
    
    func main() {
        i := &inventory.TemplateInventory{
            Name: "test-2",
            Data: map[string]any{
                "Name": "test-2",
                "Namespace": "tests",
            },
        }
    
        if err := i.Load(context.TODO()); err != nil {
            panic(err)
        }
    
        for _, obj := range i.Objects() {
            if sec, ok := obj.(*corev1.Secret); ok {
                fmt.Println(sec.Namespace, "/", sec.Name, ":", sec.Type)
                fmt.Println(string(sec.Data["hello"]))
            }
        }
    }

Author's Checklist

For anything in this list which will not be completed, please provide a reason in the MR discussion.

Required

  • Ensure a release milestone is set.
  • MR title and description are up to date, accurate, and descriptive.
  • MR targeting the appropriate branch.
  • MR has a green pipeline on GitLab.com.
  • When ready for review, MR is labeled workflowready for review per the MR workflow.

Expected

  • Test plan indicating conditions for success has been posted and passes.
  • Documentation is created or updated.
  • Tests are added.

Related issues

Related to #19 (closed)

Edited by Hossein Pursultani

Merge request reports