kubernetes generated names

Naming is hard

Naming is hard, especially for kubernetes resources that are some of the lowest possible deployable units, like pods, replication controllers and jobs.

Some of these resources cannot be changed once they are created. e.g. re-running a job with a different image version is not possible without changing it’s name.

But there’s a generateName field on the yaml manifests that we can use instead:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
apiVersion: batch/v1
kind: Job
metadata:
  generateName: rerunnablejob-
  labels:
    app: rerunnablejob
spec:
  template:
    spec:
      containers:
        - name: myjob
          image: my/image:v0.0.1
          args: ["container", "arguments"]
      restartPolicy: Never

Now when the job is started it will get a unique generated name like: rerunnablejob-zgj92.

Then name being different allows kubectl apply -f job.yaml as many times as you want with different images / versions and new jobs will be created for each one.

Note; You will need to use kubectl create and not kubectl apply for generate name to work well.

Kustomize

At the time of writing the kustomize cli tool fails to build resources that do not have a metadata.name kubernetes-sigs/kustomize#641

This means that if we do something like:

1
kustomize build | kubectl create -f -

We will get an error that says:

1
Error: loadResMapFromBasesAndResources: rawResources failed to read Resources: Missing metadata.name in object ...

While the issue is being fixed, we can strip the name using sed:

1
kustomize build | sed -e 's/^  name.*$//g' | kubectl create -f -