<@ULVA73B9P> Is it possible to cancel the executio...
# ask-marvin
d
@Marvin Is it possible to cancel the execution of a KubernetesJob (the JobBlock) early? If so, how?
m
thought for 315.1 seconds
Short answer: yes. The “right” way depends on how you’re running the job. 1) If the job was started by a Prefect 3.x flow run via a Kubernetes work pool/worker - Cancel the flow run. The Kubernetes worker will detect the cancellation and delete the Kubernetes Job/Pod for you. - UI: Click “Cancel” on the flow run - CLI:
Copy code
prefect flow-run cancel <FLOW_RUN_ID>
- API (programmatic):
Copy code
from prefect.client.orchestration import get_client
    from prefect.states import Cancelled

    async def cancel_run(flow_run_id: str):
        async with get_client() as client:
            await client.set_flow_run_state(flow_run_id, Cancelled())
- Notes: - Make sure your Kubernetes worker is running and has permissions to delete Jobs/Pods. - If the worker could not record the infrastructure ID for some reason, Prefect will mark the run cancelled but may not be able to force-kill the k8s job. Helpful docs: Cancel workflows, Kubernetes worker guide 2) If you started a Kubernetes job yourself using prefect-kubernetes “job” helpers (outside of a deployed flow run) - You can delete the Job directly using prefect-kubernetes helpers or kubectl. For example:
Copy code
from prefect_kubernetes.credentials import KubernetesCredentials
  from <http://prefect_kubernetes.jobs|prefect_kubernetes.jobs> import delete_namespaced_job
  from kubernetes.client import V1DeleteOptions

  creds = KubernetesCredentials()  # configure via env or explicit settings
  delete_namespaced_job(
      kubernetes_credentials=creds,
      job_name="my-job-name",
      namespace="my-namespace",
      delete_options=V1DeleteOptions(propagation_policy="Foreground")  # delete pods too
  )
- Equivalent with kubectl:
Copy code
kubectl delete job my-job-name -n my-namespace --wait=true
A few practical tips - Kubernetes will send SIGTERM to your container(s) and honor `terminationGracePeriodSeconds`; ensure your code handles SIGTERM for a clean shutdown. - In Prefect 3.x, infrastructure blocks from 2.x (like the old “KubernetesJob” infrastructure block) have been replaced by work pools/workers. If you’re still on 2.x or using legacy blocks, consider upgrading to 3.x. Would you share which setup you’re using? - Prefect 3.x with a Kubernetes work pool/worker running your flows - Or ad-hoc jobs launched via
<http://prefect_kubernetes.jobs|prefect_kubernetes.jobs>
(or legacy 2.x “KubernetesJob” block) With that, I can tailor the exact steps.