from kubernetes.client import BatchV1Api, V1Job, V1Container, V1ObjectMeta, V1PodTemplateSpec, V1PodSpec, V1JobSpec, \
V1Volume, V1PersistentVolumeClaimVolumeSource, V1VolumeMount, V1ResourceRequirements
from kubernetes.config import load_kube_config
def create_job_object():
container = V1Container(
name="ttt",
image="alpine",
command=["sleep", "10"],
volume_mounts=[V1VolumeMount(name='data', mount_path='/data', sub_path='your/sub/path', read_only=True)],
resources=V1ResourceRequirements()
)
template = V1PodTemplateSpec(
metadata=V1ObjectMeta(labels={"app": "ttt"}),
spec=V1PodSpec(
restart_policy="Never",
containers=[container],
volumes=[V1Volume(
name='data',
persistent_volume_claim=V1PersistentVolumeClaimVolumeSource(claim_name='data')
)]
)
)
spec = V1JobSpec(
template=template,
backoff_limit=1,
ttl_seconds_after_finished=5,
active_deadline_seconds=10
)
return V1Job(
api_version="batch/v1",
kind="Job",
metadata=V1ObjectMeta(name='ttt'),
spec=spec
)
load_kube_config(config_file='kube_config')
batch = BatchV1Api()
job = {
'apiVersion': 'batch/v1',
'kind': 'Job',
'metadata': {
'name': 'ttt'
},
'spec': {
'backoffLimit': 0,
'activeDeadlineSeconds': 100,
'ttlSecondsAfterFinished': 60,
'template': {
'spec': {
'restartPolicy': 'Never',
'nodeSelector': {
"gpu": "1"
},
'containers': [{
'name': 'ttt',
'image': 'alpine',
'command': ['bash', '-c'],
'args': ['ls /data && ls /tmp'],
'volumeMounts': [{
'name': 'data',
'mountPath': '/data',
'subPath': 'your/sub/path',
'readOnly': True
}]
}],
'volumes': [{
'name': 'data',
'persistentVolumeClaim': {
'claimName': 'data'
}
}]
}
}
}
}
api_response = batch.create_namespaced_job(body=job, namespace="default")
r = batch.read_namespaced_job(name='ttt', namespace='default')
print(r.status)
{'active': None,
'completion_time': datetime.datetime(2021, 2, 20, 1, 31, 16, tzinfo=tzutc()),
'conditions': [{'last_probe_time': datetime.datetime(2021, 2, 20, 1, 31, 16, tzinfo=tzutc()),
'last_transition_time': datetime.datetime(2021, 2, 20, 1, 31, 16, tzinfo=tzutc()),
'message': None,
'reason': None,
'status': 'True',
'type': 'Complete'}],
'failed': None,
'start_time': datetime.datetime(2021, 2, 20, 1, 31, 14, tzinfo=tzutc()),
'succeeded': 1}