|
| 1 | +--- |
| 2 | +title: Effective KRM functions |
| 3 | +linkTitle: Effective KRM functions |
| 4 | +description: Practical patterns for selecting, reading, and updating resources in a KRM function. |
| 5 | +toc_hide: false |
| 6 | +menu: |
| 7 | + main: |
| 8 | + parent: "KRM Function Developer Guide" |
| 9 | + weight: 25 |
| 10 | +--- |
| 11 | +This guide covers patterns for writing KRM functions that go beyond the basic |
| 12 | +tutorial. Read [Tutorial]({{% relref "/guides/krm-functions/tutorial" %}}) and |
| 13 | +[Interfaces]({{% relref "/guides/krm-functions/interfaces" %}}) first. |
| 14 | + |
| 15 | +The examples use the [KRM function SDK](https://pkg.go.dev/github.com/kptdev/krm-functions-sdk/go/fn). |
| 16 | +The resource types and selector functions live in the |
| 17 | +[`kubeobject` package](https://pkg.go.dev/github.com/kptdev/kpt/api/kubeobject), so |
| 18 | +import it alongside the SDK. The examples refer to it as `kubeobject`. |
| 19 | + |
| 20 | +## Prerequisites |
| 21 | + |
| 22 | +- [Install kpt]({{% relref "/installation" %}}) |
| 23 | +- [Install Docker](https://docs.docker.com/get-docker/) |
| 24 | +- Go 1.24 or later, the minimum version the SDK requires |
| 25 | + |
| 26 | +## Read configuration |
| 27 | + |
| 28 | +The function config arrives as a `KubeObject` in the `functionConfig` argument of |
| 29 | +`Run`. Read the fields you need from it instead of defining a struct for them. |
| 30 | + |
| 31 | +```golang |
| 32 | +func (r *SetImage) Run(ctx *fn.Context, functionConfig *kubeobject.KubeObject, items kubeobject.KubeObjects, results *kubeobject.Results) bool { |
| 33 | + oldImage, _, err := functionConfig.NestedString("oldImage") |
| 34 | + if err != nil { |
| 35 | + results.ErrorE(err) |
| 36 | + return false |
| 37 | + } |
| 38 | + newImage, _, err := functionConfig.NestedString("newImage") |
| 39 | + if err != nil { |
| 40 | + results.ErrorE(err) |
| 41 | + return false |
| 42 | + } |
| 43 | + // ... use oldImage and newImage |
| 44 | + return true |
| 45 | +} |
| 46 | +``` |
| 47 | + |
| 48 | +In `main`, wrap your `Runner` with `fn.WithContext` before passing it to |
| 49 | +`fn.AsMain`, as shown in [Interfaces]({{% relref "/guides/krm-functions/interfaces" %}}). |
| 50 | +Passing it directly fails at runtime with `unknown input type`. |
| 51 | + |
| 52 | +A matching input looks like this: |
| 53 | + |
| 54 | +```yaml |
| 55 | +apiVersion: fn.kpt.dev/v1alpha1 |
| 56 | +kind: SetImage |
| 57 | +metadata: |
| 58 | + name: try-out |
| 59 | +oldImage: example |
| 60 | +newImage: my-registry/example:v2 |
| 61 | +``` |
| 62 | +
|
| 63 | +## Select KRM resources |
| 64 | +
|
| 65 | +`kubeobject.KubeObjects` is a slice of `*kubeobject.KubeObject`. Use `Where` and |
| 66 | +`WhereNot` with a predicate to narrow the set. The `GroupVersionKind` and |
| 67 | +`GroupKind` types come from `github.com/kptdev/kpt/api/schema/v1`, not from |
| 68 | +`k8s.io/apimachinery`. |
| 69 | + |
| 70 | +```golang |
| 71 | +import schema "github.com/kptdev/kpt/api/schema/v1" |
| 72 | +
|
| 73 | +// Namespace-scoped resources only. |
| 74 | +namespaced := items.Where(func(o *kubeobject.KubeObject) bool { |
| 75 | + return o.IsNamespaceScoped() |
| 76 | +}) |
| 77 | +
|
| 78 | +// Cluster-scoped resources only. |
| 79 | +clusterScoped := items.Where(func(o *kubeobject.KubeObject) bool { |
| 80 | + return o.IsClusterScoped() |
| 81 | +}) |
| 82 | +
|
| 83 | +// Deployments in the apps group, at exactly apps/v1. |
| 84 | +deployments := items.Where(kubeobject.IsGroupVersionKind(schema.GroupVersionKind{ |
| 85 | + Group: "apps", |
| 86 | + Version: "v1", |
| 87 | + Kind: "Deployment", |
| 88 | +})) |
| 89 | +
|
| 90 | +// Everything except Namespace objects, in the core group. |
| 91 | +excluded := items.WhereNot(kubeobject.IsGroupKind(schema.GroupKind{ |
| 92 | + Group: "", |
| 93 | + Kind: "Namespace", |
| 94 | +})) |
| 95 | +``` |
| 96 | + |
| 97 | +Use `kubeobject.IsGroupVersionKind` to match an exact apiVersion and kind. Use |
| 98 | +`kubeobject.IsGroupKind` to match a group and kind across all versions. `IsGVK` is |
| 99 | +deprecated, so avoid it in new code. |
| 100 | + |
| 101 | +Changes you make to the objects in `items`, or to objects returned by `Where`, are |
| 102 | +reflected in the output, because these are the same objects. Reassigning `items` |
| 103 | +or building a filtered slice does not change the output. The SDK emits the list it |
| 104 | +passed to `Run`, so a `Runner` can't add or remove resources. To add or remove |
| 105 | +resources, implement a `ResourceListProcessor` instead, as described in |
| 106 | +[Interfaces]({{% relref "/guides/krm-functions/interfaces" %}}). |
| 107 | + |
| 108 | +`kubeobject.IsName` matches objects by name, for example |
| 109 | +`items.Where(kubeobject.IsName("nginx"))`. |
| 110 | + |
| 111 | +`IsNamespaceScoped` is decided by a table of known kinds. For any other kind it |
| 112 | +falls back to whether `metadata.namespace` is set. A custom resource without a |
| 113 | +namespace is treated as cluster-scoped, so check the kind if this matters for |
| 114 | +your function. |
| 115 | + |
| 116 | +## Read and update fields |
| 117 | + |
| 118 | +`kubeobject.KubeObject` embeds `kubeobject.SubObject`, so both expose the same |
| 119 | +field accessors. Each nested getter returns the value, whether the field was |
| 120 | +found, and an error. |
| 121 | + |
| 122 | +```golang |
| 123 | +for _, obj := range items.Where(kubeobject.IsGroupVersionKind(schema.GroupVersionKind{ |
| 124 | + Group: "apps", |
| 125 | + Version: "v1", |
| 126 | + Kind: "Deployment", |
| 127 | +})) { |
| 128 | + replicas, found, err := obj.NestedInt64("spec", "replicas") |
| 129 | + if err != nil { |
| 130 | + results.ErrorE(err) |
| 131 | + continue |
| 132 | + } |
| 133 | + if found { |
| 134 | + fn.Logf("%s has %d replicas\n", obj.GetName(), replicas) |
| 135 | + } |
| 136 | +
|
| 137 | + strategy, _, err := obj.NestedString("spec", "strategy", "type") |
| 138 | + if err != nil { |
| 139 | + results.ErrorE(err) |
| 140 | + continue |
| 141 | + } |
| 142 | + if strategy == "Recreate" { |
| 143 | + if err := obj.SetNestedString("RollingUpdate", "spec", "strategy", "type"); err != nil { |
| 144 | + results.ErrorE(err) |
| 145 | + } |
| 146 | + } |
| 147 | +} |
| 148 | +``` |
| 149 | + |
| 150 | +Setters return an error. Check it, as shown above. |
| 151 | + |
| 152 | +## Work with sub-objects |
| 153 | + |
| 154 | +`GetMap` returns a `SubObject` for a nested map. If the field is missing, it |
| 155 | +returns `nil`, and calling a method on `nil` panics. Check each step before you |
| 156 | +chain the next one. |
| 157 | + |
| 158 | +```golang |
| 159 | +spec := deployment.GetMap("spec") |
| 160 | +if spec == nil { |
| 161 | + return true // no spec, nothing to update |
| 162 | +} |
| 163 | +template := spec.GetMap("template") |
| 164 | +if template == nil { |
| 165 | + return true |
| 166 | +} |
| 167 | +podSpec := template.GetMap("spec") |
| 168 | +if podSpec == nil { |
| 169 | + return true |
| 170 | +} |
| 171 | +
|
| 172 | +if err := podSpec.SetNestedString("ssd", "nodeSelector", "disktype"); err != nil { |
| 173 | + results.ErrorE(err) |
| 174 | +} |
| 175 | +``` |
| 176 | + |
| 177 | +## Decode into a typed struct |
| 178 | + |
| 179 | +When a resource has a shape you already model in Go, decode its sub-object into a |
| 180 | +struct with `As`. `As` returns an error on a `nil` sub-object, so it is safe to |
| 181 | +call without a check, but you still need to handle that error. |
| 182 | + |
| 183 | +```golang |
| 184 | +type deploymentSpec struct { |
| 185 | + Replicas int64 `json:"replicas"` |
| 186 | +} |
| 187 | + |
| 188 | +var spec deploymentSpec |
| 189 | +if err := deployment.GetMap("spec").As(&spec); err != nil { |
| 190 | + results.ErrorE(err) |
| 191 | + return false |
| 192 | +} |
| 193 | +fn.Logf("decoded %d replicas\n", spec.Replicas) |
| 194 | +``` |
| 195 | + |
| 196 | +`As` copies the sub-object. Changes you make to `spec` don't change the resource. |
| 197 | +To update the resource, set the fields back with the setters, such as |
| 198 | +`SetNestedString`, on the `KubeObject`. |
| 199 | + |
| 200 | +## Next steps |
| 201 | + |
| 202 | +- Read [Testing]({{% relref "/guides/krm-functions/testing" %}}) to cover your |
| 203 | + selection and update logic with golden tests. |
| 204 | +- Read [Containerizing]({{% relref "/guides/krm-functions/containerizing" %}}) to |
| 205 | + package the function as an image. |
0 commit comments