From 721d896c4bb3e25dc24fe2c7ae5847afe4942ff9 Mon Sep 17 00:00:00 2001 From: liamfallon Date: Fri, 13 Nov 2026 04:01:29 -0700 Subject: [PATCH 1/5] docs: add effective KRM functions guide Port the effective Go KRM function guide from #3367 to the current documentation tree. Rewrites examples against the current krm-functions-sdk API (Run with results and bool return, functionConfig accessors, nested getters returning value, found, err). Assisted-by: Kiro:claude-haiku-5.5 Signed-off-by: liamfallon --- .../en/book/05-developing-functions/_index.md | 2 + .../content/en/guides/krm-functions/_index.md | 2 + .../en/guides/krm-functions/effective.md | 149 ++++++++++++++++++ 3 files changed, 153 insertions(+) create mode 100644 documentation/content/en/guides/krm-functions/effective.md diff --git a/documentation/content/en/book/05-developing-functions/_index.md b/documentation/content/en/book/05-developing-functions/_index.md index ed06f4e8a8..ec213435c2 100644 --- a/documentation/content/en/book/05-developing-functions/_index.md +++ b/documentation/content/en/book/05-developing-functions/_index.md @@ -420,6 +420,8 @@ kpt fn eval ./testdata/hello-world/resources.yaml --image ${FN_CONTAINER_REGISTR - Read the [KRM Function Developer Guide]({{% relref "/guides/krm-functions" %}}) for choosing an [interface]({{% relref "/guides/krm-functions/interfaces" %}}) (`fn.Runner` vs `fn.ResourceListProcessor`), + [effective patterns]({{% relref "/guides/krm-functions/effective" %}}) for selecting + and updating resources, [testing]({{% relref "/guides/krm-functions/testing" %}}) with golden files, and [containerizing]({{% relref "/guides/krm-functions/containerizing" %}}) your function. - See other [go documentation examples](https://pkg.go.dev/github.com/kptdev/krm-functions-sdk/go/fn/examples) to use KubeObject. diff --git a/documentation/content/en/guides/krm-functions/_index.md b/documentation/content/en/guides/krm-functions/_index.md index efa109c729..686512b1ec 100644 --- a/documentation/content/en/guides/krm-functions/_index.md +++ b/documentation/content/en/guides/krm-functions/_index.md @@ -17,6 +17,8 @@ then dig into the topic guides as needed. - [Interfaces]({{% relref "/guides/krm-functions/interfaces" %}}) — choose between `fn.Runner` (transformers, validators) and `fn.ResourceListProcessor` (generators, complex functions). +- [Effective KRM functions]({{% relref "/guides/krm-functions/effective" %}}) — patterns + for selecting, reading, and updating resources. - [Testing]({{% relref "/guides/krm-functions/testing" %}}) — golden test patterns and unit testing in depth. - [Containerizing]({{% relref "/guides/krm-functions/containerizing" %}}) — package diff --git a/documentation/content/en/guides/krm-functions/effective.md b/documentation/content/en/guides/krm-functions/effective.md new file mode 100644 index 0000000000..f2ff9e1f75 --- /dev/null +++ b/documentation/content/en/guides/krm-functions/effective.md @@ -0,0 +1,149 @@ +--- +title: Effective KRM functions +linkTitle: Effective KRM functions +description: Practical patterns for selecting, reading, and updating resources in a KRM function. +toc_hide: false +menu: + main: + parent: "KRM Function Developer Guide" + weight: 25 +--- +This guide covers patterns for writing KRM functions that go beyond the basic +tutorial. Read [Tutorial]({{% relref "/guides/krm-functions/tutorial" %}}) and +[Interfaces]({{% relref "/guides/krm-functions/interfaces" %}}) first. + +The examples use the [KRM function SDK](https://pkg.go.dev/github.com/kptdev/krm-functions-sdk/go/fn). + +## Prerequisites + +- [Install kpt]({{% relref "/installation" %}}) +- [Install Docker](https://docs.docker.com/get-docker/) + +## Read configuration + +The function config arrives as a `KubeObject` in the `functionConfig` argument of +`Run`. Read the fields you need from it instead of defining a struct for them. + +```golang +func (r *SetImage) Run(ctx *fn.Context, functionConfig *fn.KubeObject, items fn.KubeObjects, results *fn.Results) bool { + oldImage, _, err := functionConfig.NestedString("oldImage") + if err != nil { + results.ErrorE(err) + return false + } + newImage, _, err := functionConfig.NestedString("newImage") + if err != nil { + results.ErrorE(err) + return false + } + // ... use oldImage and newImage + return true +} +``` + +A matching input looks like this: + +```yaml +apiVersion: fn.kpt.dev/v1alpha1 +kind: SetImage +metadata: + name: try-out +oldImage: example +newImage: my-registry/example:v2 +``` + +## Select KRM resources + +`fn.KubeObjects` is a slice of `*fn.KubeObject`. Use `Where` and `WhereNot` with +a predicate to narrow the set. + +```golang +// Namespace-scoped resources only. +namespaced := items.Where(func(o *fn.KubeObject) bool { + return o.IsNamespaceScoped() +}) + +// Cluster-scoped resources only. +clusterScoped := items.Where(func(o *fn.KubeObject) bool { + return o.IsClusterScoped() +}) + +// Deployments in the apps/v1 group. +deployments := items.Where(fn.IsGVK("apps", "v1", "Deployment")) + +// Everything except Namespace objects. +excluded := items.WhereNot(fn.IsGVK("", "v1", "Namespace")) +``` + +`fn.IsGVK` takes group, version, and kind. Pass an empty version to match any version. + +## Read and update fields + +`KubeObject` embeds `SubObject`, so both expose the same field accessors. Each +nested getter returns the value, whether the field was found, and an error. + +```golang +for _, obj := range items.Where(fn.IsGVK("apps", "v1", "Deployment")) { + replicas, found, err := obj.NestedInt64("spec", "replicas") + if err != nil { + results.ErrorE(err) + continue + } + if found { + fn.Logf("%s has %d replicas\n", obj.GetName(), replicas) + } + + strategy, _, err := obj.NestedString("spec", "strategy", "type") + if err != nil { + results.ErrorE(err) + continue + } + if strategy == "Recreate" { + if err := obj.SetNestedString("RollingUpdate", "spec", "strategy", "type"); err != nil { + results.ErrorE(err) + } + } +} +``` + +Setters return an error. Check it, as shown above. + +## Work with sub-objects + +`GetMap` returns a `SubObject` for a nested map, so you can chain lookups without +repeating the full path. + +```golang +spec := deployment.GetMap("spec") +template := spec.GetMap("template") +nodeSelector := template.GetMap("spec").GetMap("nodeSelector") + +if err := nodeSelector.SetNestedString("ssd", "disktype"); err != nil { + results.ErrorE(err) +} +``` + +## Decode into a typed struct + +When a resource has a shape you already model in Go, decode its sub-object into a +struct with `As`. + +```golang +type deploymentSpec struct { + Replicas int64 `json:"replicas"` +} + +var spec deploymentSpec +if err := deployment.GetMap("spec").As(&spec); err != nil { + results.ErrorE(err) + return false +} +fn.Logf("decoded %d replicas\n", spec.Replicas) +``` + +## Next steps + +- Read [Testing]({{% relref "/guides/krm-functions/testing" %}}) to cover your + selection and update logic with golden tests. +- Read [Containerizing]({{% relref "/guides/krm-functions/containerizing" %}}) to + package the function as an image. From e3c0041a35ac9b3cd74fba8493c8e5623011ad71 Mon Sep 17 00:00:00 2001 From: liamfallon Date: Fri, 13 Nov 2026 04:16:14 -0700 Subject: [PATCH 2/5] Update effective.md for the current SDK Signed-off-by: liamfallon --- .../en/guides/krm-functions/effective.md | 62 +++++++++++++++---- 1 file changed, 49 insertions(+), 13 deletions(-) diff --git a/documentation/content/en/guides/krm-functions/effective.md b/documentation/content/en/guides/krm-functions/effective.md index f2ff9e1f75..94d11deb34 100644 --- a/documentation/content/en/guides/krm-functions/effective.md +++ b/documentation/content/en/guides/krm-functions/effective.md @@ -41,6 +41,10 @@ func (r *SetImage) Run(ctx *fn.Context, functionConfig *fn.KubeObject, items fn. } ``` +In `main`, wrap your `Runner` with `fn.WithContext` before passing it to +`fn.AsMain`, as shown in [Interfaces]({{% relref "/guides/krm-functions/interfaces" %}}). +Passing it directly fails at runtime with `unknown input type`. + A matching input looks like this: ```yaml @@ -55,9 +59,12 @@ newImage: my-registry/example:v2 ## Select KRM resources `fn.KubeObjects` is a slice of `*fn.KubeObject`. Use `Where` and `WhereNot` with -a predicate to narrow the set. +a predicate to narrow the set. The `GroupVersionKind` and `GroupKind` types come from +`github.com/kptdev/kpt/api/schema/v1`, not from `k8s.io/apimachinery`. ```golang +import schema "github.com/kptdev/kpt/api/schema/v1" + // Namespace-scoped resources only. namespaced := items.Where(func(o *fn.KubeObject) bool { return o.IsNamespaceScoped() @@ -68,14 +75,28 @@ clusterScoped := items.Where(func(o *fn.KubeObject) bool { return o.IsClusterScoped() }) -// Deployments in the apps/v1 group. -deployments := items.Where(fn.IsGVK("apps", "v1", "Deployment")) - -// Everything except Namespace objects. -excluded := items.WhereNot(fn.IsGVK("", "v1", "Namespace")) +// Deployments in the apps group, at exactly apps/v1. +deployments := items.Where(fn.IsGroupVersionKind(schema.GroupVersionKind{ + Group: "apps", + Version: "v1", + Kind: "Deployment", +})) + +// Everything except Namespace objects, in the core group. +excluded := items.WhereNot(fn.IsGroupKind(schema.GroupKind{ + Group: "", + Kind: "Namespace", +})) ``` -`fn.IsGVK` takes group, version, and kind. Pass an empty version to match any version. +Use `fn.IsGroupVersionKind` to match an exact apiVersion and kind. Use +`fn.IsGroupKind` to match a group and kind across all versions. `IsGVK` is +deprecated, so avoid it in new code. + +`IsNamespaceScoped` is decided by a table of known kinds. For any other kind it +falls back to whether `metadata.namespace` is set. A custom resource without a +namespace is treated as cluster-scoped, so check the kind if this matters for +your function. ## Read and update fields @@ -83,7 +104,11 @@ excluded := items.WhereNot(fn.IsGVK("", "v1", "Namespace")) nested getter returns the value, whether the field was found, and an error. ```golang -for _, obj := range items.Where(fn.IsGVK("apps", "v1", "Deployment")) { +for _, obj := range items.Where(fn.IsGroupVersionKind(schema.GroupVersionKind{ + Group: "apps", + Version: "v1", + Kind: "Deployment", +})) { replicas, found, err := obj.NestedInt64("spec", "replicas") if err != nil { results.ErrorE(err) @@ -110,15 +135,25 @@ Setters return an error. Check it, as shown above. ## Work with sub-objects -`GetMap` returns a `SubObject` for a nested map, so you can chain lookups without -repeating the full path. +`GetMap` returns a `SubObject` for a nested map. If the field is missing, it +returns `nil`, and calling a method on `nil` panics. Check each step before you +chain the next one. ```golang spec := deployment.GetMap("spec") +if spec == nil { + return true // no spec, nothing to update +} template := spec.GetMap("template") -nodeSelector := template.GetMap("spec").GetMap("nodeSelector") +if template == nil { + return true +} +podSpec := template.GetMap("spec") +if podSpec == nil { + return true +} -if err := nodeSelector.SetNestedString("ssd", "disktype"); err != nil { +if err := podSpec.SetNestedString("ssd", "nodeSelector", "disktype"); err != nil { results.ErrorE(err) } ``` @@ -126,7 +161,8 @@ if err := nodeSelector.SetNestedString("ssd", "disktype"); err != nil { ## Decode into a typed struct When a resource has a shape you already model in Go, decode its sub-object into a -struct with `As`. +struct with `As`. `As` returns an error on a `nil` sub-object, so it is safe to +call without a check, but you still need to handle that error. ```golang type deploymentSpec struct { From 14f74dbbbfbe8c3ae007ad7a7ec7ee35a2accdd9 Mon Sep 17 00:00:00 2001 From: liamfallon Date: Fri, 13 Nov 2026 04:20:01 -0700 Subject: [PATCH 3/5] docs: address review points in effective KRM functions guide Add the minimum Go version, note that items are modified in place, add fn.IsName, and explain that As decodes a copy of the sub-object. Assisted-by: Kiro:claude-haiku-5.5 Signed-off-by: liamfallon --- .../content/en/guides/krm-functions/effective.md | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/documentation/content/en/guides/krm-functions/effective.md b/documentation/content/en/guides/krm-functions/effective.md index 94d11deb34..1431d6751f 100644 --- a/documentation/content/en/guides/krm-functions/effective.md +++ b/documentation/content/en/guides/krm-functions/effective.md @@ -18,6 +18,7 @@ The examples use the [KRM function SDK](https://pkg.go.dev/github.com/kptdev/krm - [Install kpt]({{% relref "/installation" %}}) - [Install Docker](https://docs.docker.com/get-docker/) +- Go 1.24 or later, the minimum version the SDK requires ## Read configuration @@ -93,6 +94,11 @@ Use `fn.IsGroupVersionKind` to match an exact apiVersion and kind. Use `fn.IsGroupKind` to match a group and kind across all versions. `IsGVK` is deprecated, so avoid it in new code. +The objects in `items` are modified in place, and the function's output is the +set of objects you leave in `items`. You don't return a new list. + +`fn.IsName` matches objects by name, for example `items.Where(fn.IsName("nginx"))`. + `IsNamespaceScoped` is decided by a table of known kinds. For any other kind it falls back to whether `metadata.namespace` is set. A custom resource without a namespace is treated as cluster-scoped, so check the kind if this matters for @@ -177,6 +183,10 @@ if err := deployment.GetMap("spec").As(&spec); err != nil { fn.Logf("decoded %d replicas\n", spec.Replicas) ``` +`As` copies the sub-object. Changes you make to `spec` don't change the resource. +To update the resource, set the fields back with the setters, such as +`SetNestedString`, on the `KubeObject`. + ## Next steps - Read [Testing]({{% relref "/guides/krm-functions/testing" %}}) to cover your From 3290ee4b83d157fa7d45c13d6fdb5cc58ae16877 Mon Sep 17 00:00:00 2001 From: liamfallon Date: Fri, 13 Nov 2026 04:39:45 -0700 Subject: [PATCH 4/5] Fixed copilot comments Signed-off-by: liamfallon --- .../en/guides/krm-functions/effective.md | 34 +++++++++++-------- 1 file changed, 20 insertions(+), 14 deletions(-) diff --git a/documentation/content/en/guides/krm-functions/effective.md b/documentation/content/en/guides/krm-functions/effective.md index 1431d6751f..27e751be64 100644 --- a/documentation/content/en/guides/krm-functions/effective.md +++ b/documentation/content/en/guides/krm-functions/effective.md @@ -13,6 +13,9 @@ tutorial. Read [Tutorial]({{% relref "/guides/krm-functions/tutorial" %}}) and [Interfaces]({{% relref "/guides/krm-functions/interfaces" %}}) first. The examples use the [KRM function SDK](https://pkg.go.dev/github.com/kptdev/krm-functions-sdk/go/fn). +The resource types and selector functions live in the +[`kubeobject` package](https://pkg.go.dev/github.com/kptdev/kpt/api/kubeobject), so +import it alongside the SDK. The examples refer to it as `kubeobject`. ## Prerequisites @@ -26,7 +29,7 @@ The function config arrives as a `KubeObject` in the `functionConfig` argument o `Run`. Read the fields you need from it instead of defining a struct for them. ```golang -func (r *SetImage) Run(ctx *fn.Context, functionConfig *fn.KubeObject, items fn.KubeObjects, results *fn.Results) bool { +func (r *SetImage) Run(ctx *fn.Context, functionConfig *kubeobject.KubeObject, items kubeobject.KubeObjects, results *kubeobject.Results) bool { oldImage, _, err := functionConfig.NestedString("oldImage") if err != nil { results.ErrorE(err) @@ -59,45 +62,47 @@ newImage: my-registry/example:v2 ## Select KRM resources -`fn.KubeObjects` is a slice of `*fn.KubeObject`. Use `Where` and `WhereNot` with -a predicate to narrow the set. The `GroupVersionKind` and `GroupKind` types come from -`github.com/kptdev/kpt/api/schema/v1`, not from `k8s.io/apimachinery`. +`kubeobject.KubeObjects` is a slice of `*kubeobject.KubeObject`. Use `Where` and +`WhereNot` with a predicate to narrow the set. The `GroupVersionKind` and +`GroupKind` types come from `github.com/kptdev/kpt/api/schema/v1`, not from +`k8s.io/apimachinery`. ```golang import schema "github.com/kptdev/kpt/api/schema/v1" // Namespace-scoped resources only. -namespaced := items.Where(func(o *fn.KubeObject) bool { +namespaced := items.Where(func(o *kubeobject.KubeObject) bool { return o.IsNamespaceScoped() }) // Cluster-scoped resources only. -clusterScoped := items.Where(func(o *fn.KubeObject) bool { +clusterScoped := items.Where(func(o *kubeobject.KubeObject) bool { return o.IsClusterScoped() }) // Deployments in the apps group, at exactly apps/v1. -deployments := items.Where(fn.IsGroupVersionKind(schema.GroupVersionKind{ +deployments := items.Where(kubeobject.IsGroupVersionKind(schema.GroupVersionKind{ Group: "apps", Version: "v1", Kind: "Deployment", })) // Everything except Namespace objects, in the core group. -excluded := items.WhereNot(fn.IsGroupKind(schema.GroupKind{ +excluded := items.WhereNot(kubeobject.IsGroupKind(schema.GroupKind{ Group: "", Kind: "Namespace", })) ``` -Use `fn.IsGroupVersionKind` to match an exact apiVersion and kind. Use -`fn.IsGroupKind` to match a group and kind across all versions. `IsGVK` is +Use `kubeobject.IsGroupVersionKind` to match an exact apiVersion and kind. Use +`kubeobject.IsGroupKind` to match a group and kind across all versions. `IsGVK` is deprecated, so avoid it in new code. The objects in `items` are modified in place, and the function's output is the set of objects you leave in `items`. You don't return a new list. -`fn.IsName` matches objects by name, for example `items.Where(fn.IsName("nginx"))`. +`kubeobject.IsName` matches objects by name, for example +`items.Where(kubeobject.IsName("nginx"))`. `IsNamespaceScoped` is decided by a table of known kinds. For any other kind it falls back to whether `metadata.namespace` is set. A custom resource without a @@ -106,11 +111,12 @@ your function. ## Read and update fields -`KubeObject` embeds `SubObject`, so both expose the same field accessors. Each -nested getter returns the value, whether the field was found, and an error. +`kubeobject.KubeObject` embeds `kubeobject.SubObject`, so both expose the same +field accessors. Each nested getter returns the value, whether the field was +found, and an error. ```golang -for _, obj := range items.Where(fn.IsGroupVersionKind(schema.GroupVersionKind{ +for _, obj := range items.Where(kubeobject.IsGroupVersionKind(schema.GroupVersionKind{ Group: "apps", Version: "v1", Kind: "Deployment", From 17ed85c2a9938caab969ee6a1c48c9ad491b0656 Mon Sep 17 00:00:00 2001 From: liamfallon Date: Fri, 13 Nov 2026 04:42:16 -0700 Subject: [PATCH 5/5] Address copilot comment Signed-off-by: liamfallon --- .../content/en/guides/krm-functions/effective.md | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/documentation/content/en/guides/krm-functions/effective.md b/documentation/content/en/guides/krm-functions/effective.md index 27e751be64..71c104ff6d 100644 --- a/documentation/content/en/guides/krm-functions/effective.md +++ b/documentation/content/en/guides/krm-functions/effective.md @@ -98,8 +98,12 @@ Use `kubeobject.IsGroupVersionKind` to match an exact apiVersion and kind. Use `kubeobject.IsGroupKind` to match a group and kind across all versions. `IsGVK` is deprecated, so avoid it in new code. -The objects in `items` are modified in place, and the function's output is the -set of objects you leave in `items`. You don't return a new list. +Changes you make to the objects in `items`, or to objects returned by `Where`, are +reflected in the output, because these are the same objects. Reassigning `items` +or building a filtered slice does not change the output. The SDK emits the list it +passed to `Run`, so a `Runner` can't add or remove resources. To add or remove +resources, implement a `ResourceListProcessor` instead, as described in +[Interfaces]({{% relref "/guides/krm-functions/interfaces" %}}). `kubeobject.IsName` matches objects by name, for example `items.Where(kubeobject.IsName("nginx"))`.