Skip to content

Instantly share code, notes, and snippets.

@bantic
Last active January 28, 2022 11:57
Show Gist options
  • Save bantic/7a714ab4be6dfb61a1cada8b597cabe1 to your computer and use it in GitHub Desktop.
Save bantic/7a714ab4be6dfb61a1cada8b597cabe1 to your computer and use it in GitHub Desktop.
Example using kubernetes StatefulSet to target a CronJob to a specific pod

Example showing how to use a StatefulSet in coordination with a CronJob to run a scheduled command on a specific pod.

Download k8s.yaml locally and then run:

kubectl apply -f k8s.yaml && \
  kubectl rollout status statefulset/web && \
  sleep 65 && \
  for podNum in 0 1 2; do echo -n "Pod $podNum: "; kubectl exec pod/web-$podNum -- ls -1 / | grep cron || echo "<notfound>"; done

Expected output:

statefulset.apps/web created
cronjob.batch/crontest created
Waiting for 3 pods to be ready...
Waiting for 2 pods to be ready...
Waiting for 1 pods to be ready...
partitioned roll out complete: 3 new pods have been updated...
Pod 0: <notfound>
Pod 1: ran-cron          // <-- cronjob runs against pod 1 only
Pod 2: <notfound>
# Slightly modified from the StatefulSet example at
# https://kubernetes.io/docs/concepts/workloads/controllers/statefulset/
apiVersion: apps/v1
kind: StatefulSet
metadata:
name: web
spec:
selector:
matchLabels:
app: nginx # has to match .spec.template.metadata.labels
serviceName: "nginx"
replicas: 3 # by default is 1
template:
metadata:
labels:
app: nginx # has to match .spec.selector.matchLabels
spec:
containers:
- name: nginx
image: alpine:latest
command: [ "/bin/sh", "-c", "--" ]
args: [ "while true; do sleep 30; done;" ]
---
apiVersion: batch/v1beta1
kind: CronJob
metadata:
name: crontest
spec:
schedule: "* * * * *"
jobTemplate:
spec:
template:
spec:
containers:
- name: crontest
image: alpine/k8s:1.20.7
imagePullPolicy: IfNotPresent
command:
- /bin/sh
- -c
- kubectl exec pod/web-1 -- touch ran-cron
restartPolicy: OnFailure
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment