Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
94 changes: 15 additions & 79 deletions pkg/templates/templates.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,31 +17,25 @@ limitations under the License.
package templates

import (
"bytes"
"context"
"fmt"
"io"
"os"
"strings"
"text/template"

"k8s.io/klog/v2"
"k8s.io/kops/pkg/apis/kops"
"k8s.io/kops/upup/pkg/fi"
"k8s.io/kops/util/pkg/vfs"
)

type Templates struct {
cluster *kops.Cluster
resources map[string]fi.Resource
TemplateFunctions template.FuncMap
resources map[string]fi.Resource
isTemplate map[string]bool
}

func LoadTemplates(ctx context.Context, cluster *kops.Cluster, base vfs.Path) (*Templates, error) {
func LoadTemplates(ctx context.Context, base vfs.Path) (*Templates, error) {
t := &Templates{
cluster: cluster,
resources: make(map[string]fi.Resource),
TemplateFunctions: make(template.FuncMap),
resources: make(map[string]fi.Resource),
isTemplate: make(map[string]bool),
}
err := t.loadFrom(ctx, base)
if err != nil {
Expand All @@ -54,6 +48,11 @@ func (t *Templates) Find(key string) fi.Resource {
return t.resources[key]
}

// IsTemplate reports whether key was loaded from a file ending in .template.
func (t *Templates) IsTemplate(key string) bool {
return t.isTemplate[key]
}

func (t *Templates) loadFrom(ctx context.Context, base vfs.Path) error {
files, err := base.ReadTree(ctx)
if err != nil {
Expand All @@ -75,74 +74,11 @@ func (t *Templates) loadFrom(ctx context.Context, base vfs.Path) error {
return fmt.Errorf("error getting relative path for %s", f)
}

var resource fi.Resource
if strings.HasSuffix(key, ".template") {
key = strings.TrimSuffix(key, ".template")
klog.V(6).Infof("loading (templated) resource %q", key)

resource = &templateResource{
template: string(contents),
loader: t,
key: key,
}
} else {
klog.V(6).Infof("loading resource %q", key)
resource = fi.NewBytesResource(contents)

}

t.resources[key] = resource
isTemplate := strings.HasSuffix(key, ".template")
key = strings.TrimSuffix(key, ".template")
klog.V(6).Infof("loading resource %q", key)
t.resources[key] = fi.NewBytesResource(contents)
t.isTemplate[key] = isTemplate
}
return nil
}

func (l *Templates) executeTemplate(key string, d string) (string, error) {
t := template.New(key)

funcMap := make(template.FuncMap)
// funcMap["Args"] = func() []string {
// return args
//}
//funcMap["RenderResource"] = func(resourceName string, args []string) (string, error) {
// return l.renderResource(resourceName, args)
//}
for k, fn := range l.TemplateFunctions {
funcMap[k] = fn
}
t.Funcs(funcMap)

t.Option("missingkey=zero")

spec := l.cluster.Spec

_, err := t.Parse(d)
if err != nil {
return "", fmt.Errorf("error parsing template %q: %v", key, err)
}

var buffer bytes.Buffer
err = t.ExecuteTemplate(&buffer, key, spec)
if err != nil {
return "", fmt.Errorf("error executing template %q: %v", key, err)
}

return buffer.String(), nil
}

type templateResource struct {
key string
loader *Templates
template string
}

var _ fi.Resource = &templateResource{}

func (a *templateResource) Open() (io.Reader, error) {
var err error
result, err := a.loader.executeTemplate(a.key, a.template)
if err != nil {
return nil, fmt.Errorf("error executing resource template %q: %v", a.key, err)
}
reader := bytes.NewReader([]byte(result))
return reader, nil
}
58 changes: 58 additions & 0 deletions pkg/templates/templates_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
/*
Copyright 2026 The Kubernetes Authors.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

package templates

import (
"context"
"os"
"path/filepath"
"testing"

"k8s.io/kops/util/pkg/vfs"
)

func TestLoadTemplatesTracksTemplateSources(t *testing.T) {
dir := t.TempDir()
if err := os.MkdirAll(filepath.Join(dir, "addons", "example"), 0755); err != nil {
t.Fatalf("creating addon dir: %v", err)
}
if err := os.WriteFile(filepath.Join(dir, "addons", "example", "plain.yaml"), []byte("plain"), 0644); err != nil {
t.Fatalf("writing plain resource: %v", err)
}
if err := os.WriteFile(filepath.Join(dir, "addons", "example", "rendered.yaml.template"), []byte("template"), 0644); err != nil {
t.Fatalf("writing template resource: %v", err)
}

templates, err := LoadTemplates(context.Background(), vfs.NewFSPath(dir))
if err != nil {
t.Fatalf("loading templates: %v", err)
}

if templates.Find("addons/example/plain.yaml") == nil {
t.Fatalf("plain resource was not loaded")
}
if templates.IsTemplate("addons/example/plain.yaml") {
t.Fatalf("plain resource reported as template")
}

if templates.Find("addons/example/rendered.yaml") == nil {
t.Fatalf("template resource was not loaded under trimmed key")
}
if !templates.IsTemplate("addons/example/rendered.yaml") {
t.Fatalf("template resource did not report template source")
}
}
15 changes: 6 additions & 9 deletions upup/pkg/fi/cloudup/apply_cluster.go
Original file line number Diff line number Diff line change
Expand Up @@ -513,9 +513,10 @@ func (c *ApplyClusterCmd) Run(ctx context.Context) (*ApplyResults, error) {
}
}

tf := &TemplateFunctions{
KopsModelContext: *modelContext,
cloud: cloud,
addonRenderer := &addonTemplateRenderer{
modelContext: modelContext,
cloud: cloud,
secretStore: secretStore,
}

nodeUpAssets, err := nodemodel.BuildNodeUpAssets(ctx, assetBuilder)
Expand All @@ -534,22 +535,18 @@ func (c *ApplyClusterCmd) Run(ctx context.Context) (*ApplyResults, error) {
}

{
templates, err := templates.LoadTemplates(ctx, cluster, models.NewAssetPath("cloudup/resources"))
templates, err := templates.LoadTemplates(ctx, models.NewAssetPath("cloudup/resources"))
if err != nil {
return nil, fmt.Errorf("error loading templates: %v", err)
}

err = tf.AddTo(templates.TemplateFunctions, secretStore)
if err != nil {
return nil, err
}

bcb := bootstrapchannelbuilder.NewBootstrapChannelBuilder(
modelContext,
clusterLifecycle,
assetBuilder,
templates,
addons,
addonRenderer,
)

l.Builders = append(l.Builders,
Expand Down
Loading
Loading