Error when trying to create Kubernetes job

11/2/2018

I've defined this method, it should create a Kubernetes job for me.

def make_job():
    job = client.V1Job()
    job.metadata = client.V1ObjectMeta()
    job.metadata.name = "process"
    job.spec = client.V1JobSpec()
    job.spec.template = client.V1PodTemplate()
    job.spec.template.spec = client.V1PodTemplateSpec()
    job.spec.template.spec.restart_policy = "Never"
    job.spec.template.spec.containers = [        make_container()    ]
    return job

However, it returns an error on this line.

job.spec = client.V1JobSpec()

Saying

ValueError: Invalid value for `template`, must not be `None`

I wonder if I am doing something wrong here, and if so, what am I doing wrong here?

EDIT:

I've solved the error with this change

job.spec = client.V1JobSpec(template=client.V1PodTemplate)
-- Rodi
kubernetes
python
yaml

1 Answer

11/2/2018

As you have already figured out, it is not possible to construct a Job.Spec without injecting its template, something that is set on stone in the Job documentation.

The .spec.template is the only required field of the .spec.

The .spec.template is a pod template. It has exactly the same schema as a pod, except it is nested and does not have an apiVersion or kind.

Taking a look onto the Python's Kubernetes Client implementation of the V1JobSpec, it's possible to verify that the spec property is marked as non-optional, contrary to the other properties.

So by constructing the template beforehand and injecting it while constructing the JobSpec does solve the issue:

job.spec.template = client.V1PodTemplate()
job.spec.template.spec = client.V1PodTemplateSpec()
job.spec.template.spec.restart_policy = "Never"
job.spec.template.spec.containers = [    make_container()]

job.spec = client.V1JobSpec()

Following this reasoning, it does seem weird that the same does not apply in a higher-scope to the Spec property of the Job, since it's a mandatory section of the definition of a Job object.

But taking a look once again to the documentation of the client, it is possible to observe that the Spec property is marked as optional, which explains why we are able to create a Job instance, without having to inject the Spec.

-- André B
Source: StackOverflow