Delete all failed/staled jobs in Automation Suite with single script

How to delete all failed/staled jobs in Automation Suite with single script?

Description: A single script can be used to remove every failed job in the Automation Suite

  1. Create a file with the following content
vi failed-jobs.sh
#!/bin/bash
export KUBECONFIG="/etc/rancher/rke2/rke2.yaml" \
&& export PATH="$PATH:/usr/local/bin:/var/lib/rancher/rke2/bin"

# Get all jobs with a 'Failed' status
failed_jobs=$(kubectl get jobs -o json | jq -r '.items[] | select(.status.failed==1) | .metadata.name')

# Loop through the failed jobs and delete each one
for job in $failed_jobs
do
  echo "Deleting job: $job"
  kubectl delete job $job
done

echo "All failed jobs have been deleted."

  1. Grant execution permissions
chmod +x failed-jobs.sh
  1. Run the script, it will delete all the failed jobs .
./ failed-jobs.sh