Post

Kubernetes - Jobs and CronJobs

Lab assignment for creating jobs and cronjobs using kubectl

Kubernetes - Jobs and CronJobs

Prerequisites

  • Kubernetes
  • kubectl

Assignment

  • Lets start by creating a job to calculate pi using perl image and then a cronjob.

Job

1️⃣ Create a job to calculate pi using the perl image.

1
kubectl create job calculatepi --image=perl:5.34.0 -- "perl" "-Mbignum=bpi" "-wle" "print bpi(2000)"
1
watch kubectl get jobs

2️⃣ Describe the job and check if it has completed.

1
PI_POD=$(kubectl get pods | grep calculatepi | awk {'print $1'}); echo $PI_POD
1
kubectl logs $PI_POD

3️⃣ Capture the pod IP and check the logs to see the pi value calculated by the job.

1
CLUSTER_IP=$(kubectl get services | grep ClusterIP | grep nginx | awk {'print $3'}); echo $CLUSTER_IP
1
curl $CLUSTER_IP
1
kubectl delete job/calculatepi

4️⃣ Capture the yaml file from our pi job and include the completions and parallelism.

1
kubectl create job calculatepi --image=perl:5.34.0 --dry-run=client -o yaml -- "perl" "-Mbignum=bpi" "-wle" "print bpi(2000)" | tee calculatepi.yaml
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
cat <<EOF > calculatepi.yaml
apiVersion: batch/v1
kind: Job
metadata:
  creationTimestamp: null
  name: calculatepi
spec:
  completions: 20
  parallelism: 5
  template:
    metadata:
      creationTimestamp: null
    spec:
      containers:
      - command:
        - perl
        - -Mbignum=bpi
        - -wle
        - print bpi(2000)
        image: perl:5.34.0
        name: calculatepi
        resources: {}
      restartPolicy: Never
status: {}
EOF
1
kubectl apply -f calculatepi.yaml && sleep 1 && watch kubectl get pods -o wide
1
PI_POD=$(kubectl get pods | grep calculatepi | tail -1 | awk {'print $1'}); kubectl logs $PI_POD

5️⃣ Delete the job and check if the pods are deleted.

1
kubectl delete job/calculatepi
1
kubectl get pods -o wide

CronJobs

1️⃣ Create a job to calculate pi using the perl image with a schedule.

1
kubectl create cronjob calculatepi --image=perl:5.34.0 --schedule="* * * * *" -- "perl" "-Mbignum=bpi" "-wle" "print bpi(2000)"
1
watch kubectl get jobs

2️⃣ Edit the yaml file to include completions and parallelisms(completions:20 and parallelism:5).

1
kubectl edit cronjob/calculatepi
1
watch kubectl get jobs

3️⃣ Delete the cronjobs.

1
kubectl delete cronjob/calculatepi
1
kubectl get jobs
1
kubectl get pods
This post is licensed under CC BY 4.0 by the author.