Client-go - Getting the generated name before creating an object in Kubernetes using client-go

10/5/2020

Let's suppose that I have such code to generate new pod

req := &api.Pod{
		TypeMeta: unversioned.TypeMeta{
			Kind:       "Pod",
			APIVersion: "v1",
		},
		ObjectMeta: api.ObjectMeta{
			GenerateName: "name-, // need to get that name, before creating an object
		},
		Spec: api.PodSpec{
			Containers: []api.Container{
				{
					Name:  "nginx",
					Image: "nginx",
					Env:   []corev1.EnvVar{} // pass here the generated name,

				},
			},
		},
}
...
// Do some work on the generated name, before creating the resource in Kubernetes cluster
...
err := client.Create(context.Background(), req)

Is it possible to get that generated name before creating an object? Or is it possible to store that generated name in the env of the same object?

-- xaos_xv
client-go
kubernetes

1 Answer

10/5/2020

The generated name seem to be created in conjunction with the apiServer. See Issue comment and Kubernetes API Concepts - Generated values.

It is recommended to not depend on it. Typically, labels and selectors is more common in the Kubernetes ecosystem.

Env:   []corev1.EnvVar{} // pass here the generated name,

You can use the Downward API for this. Example:

          env:
            - name: POD_NAME
              valueFrom:
                fieldRef:
                  fieldPath: metadata.name
-- Jonas
Source: StackOverflow