Skip to content

Instantly share code, notes, and snippets.

@oradwell
Last active March 9, 2022 13:27
Show Gist options
  • Select an option

  • Save oradwell/8d3262326dd2b7d51c63708a698e861d to your computer and use it in GitHub Desktop.

Select an option

Save oradwell/8d3262326dd2b7d51c63708a698e861d to your computer and use it in GitHub Desktop.
Automatically delete jobs affected by CronJob Controller v2 bug which stops Job state from updating
#!/usr/bin/env bash
if [ -z "${KUBE_CONTEXT}" ]
then
echo Please provide KUBE_CONTEXT
exit 1
fi
kubectl --context="${KUBE_CONTEXT}" version > /dev/null 2>&1
if [ $? -ne 0 ]
then
echo Cannot authenticate with API server
exit 1
fi
jsonpath_template_multi='{.items[*].status.active[*].name}'
jsonpath_template_single='{.status.active[*].name}'
active_cronjobs=$(kubectl --context="${KUBE_CONTEXT}" get cronjob \
| grep " 1 " \
| cut -d' ' -f1)
if [ -z "${active_cronjobs}" ]
then
echo No active CronJobs
exit 1
fi
jsonpath_template="${jsonpath_template_multi}"
if [ "$(echo "${active_cronjobs}" | wc -l)" = "1" ]
then
jsonpath_template="${jsonpath_template_single}"
fi
active_cronjob_jobs=$(echo "${active_cronjobs}" | xargs kubectl \
--context="${KUBE_CONTEXT}" get cronjob -ojsonpath \
--template="${jsonpath_template}")
if [ -z "${active_cronjob_jobs}" ]
then
echo CronJobs have no active Jobs
exit 1
fi
completed_jobs_marked_active=$(echo "${active_cronjob_jobs}" | xargs kubectl --context="${KUBE_CONTEXT}" get job \
| grep 1/1 \
| cut -d' ' -f1)
if [ -z "${completed_jobs_marked_active}" ]
then
echo Found jobs are actually active. Nothing to do.
exit 0
fi
echo Deleting the following completed jobs:
echo "${completed_jobs_marked_active}"
sleep 3
echo "${completed_jobs_marked_active}" \
| xargs kubectl --context="${KUBE_CONTEXT}" delete job
exit 0
@pere3
Copy link

pere3 commented Jan 25, 2022

there is also a way of doing that automation through configurable application https://codeberg.org/hjacobs/kube-janitor

@oradwell
Copy link
Author

@pere3 thanks. that looks like a permanent solution. currently, I'm running this script manually

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment