k8wiz
Back to Articles

Ready to test your Kustomize knowledge? Try our Kustomize quiz!

How to copy values between resources with Kustomize replacements

Copy a field from one resource into others with Kustomize replacements: field paths, delimiter and index, create, select and reject.

9 min read
By k8wiz Team
  • kustomize
  • replacements
  • overlays

Some values in a set of manifests have to agree with each other. A Deployment needs the name of the database Service in an env var, a label should carry the image tag, and a custom resource wants the namespace the app runs in. Typing the same string in three places works until an overlay renames one of them and the others quietly fall out of sync.

Kustomize replacements copy a value from one field of one resource into fields of other resources at build time. This guide builds a small app and walks through each part of a replacement: the source, the targets, field paths, partial values with delimiter and index, missing fields with create, and target filtering with select and reject. It also covers the generated ConfigMap case, which behaves differently from what most people expect. The behaviour described here comes from the Kustomize v5.8.3 source.

How a replacement works

A replacement has one source and a list of targets. The source selects exactly one resource by group, version, kind, name and namespace, then reads one field from it with fieldPath. Each target selects any number of resources and writes the value into every path listed under fieldPaths. When you leave out fieldPath or fieldPaths, both default to metadata.name.

Replacements run as the last built-in transformer of the kustomization that declares them. Patches, namespace, namePrefix, nameSuffix, labels, annotations, replicas and images from the same kustomization have already been applied, so the replacement reads the values those produced. Hash suffixes for generated ConfigMaps and Secrets are a different story, covered further down.

Step 1: write the base

The base has a Deployment and the Service it connects to. The Deployment uses PLACEHOLDER wherever the database host goes, so a missed replacement is easy to spot in the output.

mkdir -p shop/base
cat <<'EOF' > shop/base/deployment.yaml
apiVersion: apps/v1
kind: Deployment
metadata:
  name: web
  labels:
    app.kubernetes.io/part-of: shop
spec:
  selector:
    matchLabels:
      app: web
  template:
    metadata:
      labels:
        app: web
    spec:
      containers:
      - name: web
        image: ghcr.io/example/web:1.4.2
        args:
        - --db-host=PLACEHOLDER
        env:
        - name: DB_HOST
          value: PLACEHOLDER
EOF

cat <<'EOF' > shop/base/service.yaml
apiVersion: v1
kind: Service
metadata:
  name: postgres
spec:
  selector:
    app: postgres
  ports:
  - port: 5432
EOF

cat <<'EOF' > shop/base/kustomization.yaml
apiVersion: kustomize.config.k8s.io/v1beta1
kind: Kustomization
resources:
- deployment.yaml
- service.yaml
EOF

Step 2: copy the Service name into an env var

The first replacement reads the Service's name and writes it into the DB_HOST env var. Put it in the overlay rather than the base. A replacement in the base copies postgres before the overlay adds its prefix, so the env var would point at a Service that no longer exists under that name.

mkdir -p shop/overlays/prod
cat <<'EOF' > shop/overlays/prod/kustomization.yaml
apiVersion: kustomize.config.k8s.io/v1beta1
kind: Kustomization
namePrefix: prod-
resources:
- ../../base
replacements:
- source:
    kind: Service
    name: postgres
  targets:
  - select:
      kind: Deployment
      name: prod-web
    fieldPaths:
    - spec.template.spec.containers.[name=web].env.[name=DB_HOST].value
EOF

kustomize build shop/overlays/prod

The source has no fieldPath, so it reads metadata.name. Because namePrefix runs first, that value is prod-postgres. The source selector still matches on postgres because Kustomize keeps a record of each resource's earlier names, and the target could have used web for the same reason.

        env:
        - name: DB_HOST
          value: prod-postgres

Step 3: write field paths that hit the right element

Field paths are dot separated. A number selects a list item by position, [name=web] selects list items whose name matches, and * selects every item. To use a key that contains dots, such as a label name, wrap it in brackets like metadata.labels.[app.kubernetes.io/version] or escape each dot with a backslash.

The [name=web] form is a regular expression, and it is not anchored. It matches a container named web, but also web-sidecar and legacy-web, and the replacement writes to all of them. When a pod has containers with similar names, anchor the pattern as [name=^web$].

A path that finds nothing in a selected resource stops the build. Without create, the error reads unable to find field "spec.template.spec.containers.[name=web].env.[name=DB_HOST].value" in replacement target. A target selector that matches no resources at all is not an error, so a typo in select.name silently does nothing. Check the output after adding a replacement.

Step 4: replace part of a value with delimiter and index

The container arguments hold the host inside a longer string, --db-host=PLACEHOLDER. Setting delimiter on a target splits the current value on that string, replaces the piece at index, and joins the pieces back together. Add a second target to the same replacement so both fields get the same value.

replacements:
- source:
    kind: Service
    name: postgres
  targets:
  - select:
      kind: Deployment
      name: prod-web
    fieldPaths:
    - spec.template.spec.containers.[name=web].env.[name=DB_HOST].value
  - select:
      kind: Deployment
      name: prod-web
    fieldPaths:
    - spec.template.spec.containers.[name=web].args.0
    options:
      delimiter: "="
      index: 1

The argument becomes --db-host=prod-postgres. On a target, an index past the end appends the value as a new piece, and a negative index puts it in front. With delimiter: ".", a large index and a sourceValue of svc.cluster.local, a target value of prod-postgres becomes prod-postgres.svc.cluster.local.

The same options work on the source, where they pick one piece out of the value instead. There an out of range index is an error, with a message like options.index 2 is out of bounds for value ghcr.io/example/web:1.4.2. Both sides require a scalar value, and pointing delimiter at a map or list fails with delimiter option can only be used with scalar nodes.

Step 5: create fields that don't exist yet

The next replacement copies the image tag into an app.kubernetes.io/version label. Add it to the overlay's replacements list. The source splits the image on : and takes the second piece. The label doesn't exist in the base, so the target sets create: true to add it.

- source:
    kind: Deployment
    name: web
    fieldPath: spec.template.spec.containers.[name=web].image
    options:
      delimiter: ":"
      index: 1
  targets:
  - select:
      kind: Deployment
      name: prod-web
    fieldPaths:
    - metadata.labels.[app.kubernetes.io/version]
    options:
      create: true

This replacement runs after the overlay's images entries, so a newTag set in the same overlay ends up in the label. Splitting on : breaks for a registry with a port, such as registry.local:5000/web:1.4.2, where the tag is the third piece. Adjust the index or tag images in a way that keeps the split predictable.

Step 6: choose targets with select and reject

Writing one target per Deployment doesn't scale. The kind, name, namespace, group and version fields in select and reject accept regular expressions, anchored to the whole value. labelSelector and annotationSelector take the same expressions as kubectl get -l. This target writes the host into every Deployment and StatefulSet in the shop, except anything named with a legacy- prefix.

  targets:
  - select:
      kind: Deployment|StatefulSet
      labelSelector: app.kubernetes.io/part-of=shop
    reject:
    - name: prod-legacy-.*
    fieldPaths:
    - spec.template.spec.containers.*.env.[name=DB_HOST].value

Each entry in reject is checked on its own, and a resource that matches any of them is dropped. Fields inside one entry must all match. So - kind: Job with name: migrate in the same entry rejects only the Job called migrate, while two separate entries reject every Job and everything named migrate.

Rejecting matters because of the error from step 3. If one selected workload has no DB_HOST env var, the whole build fails, so exclude it or give the target create: true.

The source side is stricter. Its name is compared literally, so name: postgres-.* selects nothing and fails with nothing selected by, followed by the selector. A source that matches two resources fails with multiple matches for selector. Add kind, name or namespace until exactly one resource fits.

Step 7: keep settings in a local ConfigMap

Some values don't belong to any real resource, like a log level shared by several workloads. You can put them in a ConfigMap that exists only at build time. Kustomize drops every resource that has the annotation config.kubernetes.io/local-config from the output, unless its value is "false".

apiVersion: v1
kind: ConfigMap
metadata:
  name: shop-settings
  annotations:
    config.kubernetes.io/local-config: "true"
data:
  HTTP_PORT: "8080"

List this file under resources and use it as a source with fieldPath: data.HTTP_PORT. The value is a string in the ConfigMap, but when it lands in a scalar field such as containerPort, Kustomize copies only the text and keeps the target's type, so the output has containerPort: 8080 as an integer. For a single fixed value you can skip the ConfigMap and use sourceValue: "8080" in place of source. A replacement takes one or the other; setting both fails with value and resource selectors are mutually exclusive.

Long replacement lists also make kustomization.yaml hard to read. Each item can be - path: replacements/db-host.yaml, pointing to a file that holds one replacement with its source and targets.

Copying a generated ConfigMap's name

Copying the name of a ConfigMap from configMapGenerator gives the name without the hash suffix. Kustomize adds hash suffixes once, after every kustomization in the tree has run its transformers, and replacements are among those transformers. In the upstream test for this case, a generated ConfigMap ends up as blue-6ct58987ht, but the copied value is blue. The test links the behaviour to kustomize issue 4034.

For the fields Kustomize already tracks, such as envFrom, volumes and configMapKeyRef in a pod spec, you don't need a replacement at all. After hashing, Kustomize rewrites those references to the new name. For a field it doesn't track, such as one in a custom resource, add a nameReference entry through the configurations field so that rewrite covers it as well. If neither fits, set generatorOptions.disableNameSuffixHash: true for that kustomization and give up the rollout on config change that the hash gives you.

Moving from vars

vars did a similar job through $(NAME) text substitution, and it is deprecated. A replacement names the target field instead, so it can't match a string by accident, and it works in any field, not only the ones vars allowed. To migrate, write one replacement per var with the var's objref as the source and its fieldref as fieldPath. Then add a target for each place the $(NAME) reference appeared and put a placeholder value back in that field.

kustomize edit fix --vars can write these for you. The guide to kustomize edit fix covers what it rewrites and how to check that the built output stays the same.

Test yourself

Ready to test your Kustomize knowledge? Try our Kustomize quiz!