PodCreate icon
If icon
Pause icon
Patch icon
SlackIncomingWebhook icon
Schedule icon

Repair Kubernetes Service selector drift and prove traffic recovers

Repair Kubernetes Service selector drift with approval, conditional patching and an in-cluster HTTP probe that proves traffic reaches Ready pods.

Categories
Infrastructure

Safety

A wrong Service selector can send requests to the wrong workload. This flow repairs one explicitly mapped Service and never guesses a Deployment from similar names.

Guard What it stops
Service annotation kestra.io/selector-repair-deployment=<deployment_name> Repairing a Service without an explicit owner-approved mapping.
kestra.io/hold-selector-repair annotation present Changing a Service intentionally isolated during an incident.
Managed-by, Argo CD or Flux metadata Fighting a manifest controller. Change its source manifest instead.
One ordinary ClusterIP Service with one TCP port and one IP family Applying an HTTP repair to headless, external, dual-stack or multi-port Services.
Stable Deployment, 1 to max_replicas replicas and exact pod ownership Confusing zero replicas, rollout lag or another workload with selector drift.
No Ready endpoints and no pods matching the old selector Replacing a selector that still serves or selects a workload.
Safe defaults plus explicit approval A scheduled inspection or dry run changing routing.
Fresh eligibility read and UID/resourceVersion/spec JSON Patch tests Applying an approved plan after the Service changes or is recreated.
Endpoint ownership and direct HTTP status verification Reporting recovery from a selector readback alone or following a redirect to another server.

How it works

  1. inspect (io.kestra.plugin.kubernetes.core.PodCreate) runs a bounded read-only API inspection inside the namespace. It reads the Service, Deployment, ReplicaSets, Pods and EndpointSlices. Plugin 1.11.4's kubectl.Get drops Service specifications and EndpointSlice addresses, so this pod preserves the full API objects needed for the comparison.
  2. The detector requires every pod selected by the Deployment's nonempty matchLabels to belong to its ReplicaSets and be Running and Ready. The Deployment must have exactly its desired updated, ready and available replicas. Drift qualifies only when the existing Service selector selects no pods and the Service has no Ready endpoints. The proposed selector is the Deployment's stable matchLabels, never a rollout hash or a guessed pod label.
  3. repair_requested enters approve (io.kestra.plugin.core.flow.Pause) only with auto_remediate=true and dry_run=false. Approval expires after 30 minutes. Declining completes without a write.
  4. recheck (PodCreate) repeats eligibility and compares the approved Service, Deployment and pod identities. repair_selector (io.kestra.plugin.kubernetes.kubectl.Patch) tests the Service UID, current resourceVersion and full spec atomically, then replaces only /spec/selector.
  5. prove_traffic (PodCreate) requires one Ready EndpointSlice endpoint per approved pod plus the expected HTTP status from http://<service>.<namespace>.svc:<port><probe_path>. It checks that the UID, ports, ClusterIP and remaining Service spec are unchanged. Redirects are rejected. prove_existing_traffic also checks an already-correct selector, so a retry after a patch still proves traffic.
  6. Any API, write or verification failure fails the execution and sends a Slack alert. The disabled ten-minute schedule forces safe inputs.

What you get

  • An explicit verdict separating selector drift from healthy routing, zero replicas, unready workloads and ambiguous ownership.
  • The approved original selector and conditional patch in Kestra storage for incident review or a conditional manual rollback.
  • Recovery evidence containing Ready endpoint identities, the HTTP status and a response-body SHA-256.

Who it's for

Platform teams whose pods stay healthy after a routing label rename while requests to their Service fail.

Why orchestrate this with Kestra

Keep the diagnosis, approval, conditional routing change and independent in-cluster recovery check in one execution. A workload restart cannot repair a selector that matches no pods.

Tested end to end

Tested on Kestra 2.0.5 with Kubernetes plugin 1.11.4, k3s v1.31.5+k3s1 and nginx 1.27.4. Two nginx pods carried app=web,route=new while the Service still selected route=old. Independent kubectl get endpointslices reads measured 0 to 2 Ready endpoints. kubectl exec deployment/web -- wget changed from connection refused, exit 1 to HTTP 200, exit 0. Both original pod UIDs, the Service UID, ClusterIP and ports were preserved. A second fresh cluster reproduced recovery and stale-approval refusal.

Case Execution Result
Healthy routing 3v4zxUngAJuz4qG8hQWTqx SUCCESS; no patch, HTTP 200
Selector drift, dry run 6YwPIgMx1OcVRlDsy10oBg SUCCESS; selector unchanged, 0 Ready endpoints
Approval declined 2DbqPybOKGbq5rxUb9mfol SUCCESS; no patch
Approved repair dRWBwF7iFkH8tBD6k6ZY7 SUCCESS; 0 to 2 Ready endpoints, HTTP 200
Repeat after repair 6AZ0wWJQzefLyocjbVKyqO SUCCESS; no patch, HTTP 200
RBAC refuses patch 4ASkrk2QVehtbR6Aec0uhw FAILED as required; selector unchanged
Hold added during approval 4jSScLWlwzmTW67yoJMdum FAILED as required before patch
Existing hold 2teROulfAMGdf9bFpbywGr SUCCESS; no patch
Manifest-managed Service 1a9Q3DLnwkjkYbNHjVbiJ5 SUCCESS; no patch
Zero replicas 3l5NyrM2WSoRCwssfX8gFs SUCCESS; no patch
Replica ceiling exceeded 1uW1JEgLQQ4ZDF2b2VodgF SUCCESS; no patch
Unrelated matching pod 7KHzzWw84ZWRgkq9IiXptL SUCCESS; no patch
Wrong expected HTTP status 1jSCKFAIogSQBxtpqJg2iU FAILED as required; HTTP 200 differs from expected 201
Retry after failed verification 6R0iITLNq9ChYZHAW30itJ SUCCESS; HTTP 200, no second patch
Fresh cluster: Approved repair 5ZyBtGKfIdeq01yOJXJ2JX SUCCESS; 0 to 2 Ready endpoints, HTTP 200
Fresh cluster: Healthy routing 3zmI2xkjlgcXPKbPEwHU9b SUCCESS; no patch, HTTP 200
Fresh cluster: Hold added during approval 3joPw8LXSG47hfVxlaqZH6 FAILED as required before patch

Prerequisites

  • A Kubernetes cluster reachable by the Kestra worker, working cluster DNS and HTTP access from inspection pods to the Service. Images must be available to cluster nodes.
  • Worker identity: create/get/list/watch/delete Pods, get pods/log, create/get pods/exec and list Events in the target namespace. Grant get/patch Services only for the selected Service using RBAC resourceNames.
  • The separate reader_service_account: get/list Services and Pods, Deployments and ReplicaSets in apps plus EndpointSlices in discovery.k8s.io. It needs no write permissions. Restrict who can edit this flow or create pods under privileged ServiceAccounts in the namespace.
  • An explicitly opted-in Service. Services with managed-by, Argo CD or Flux metadata are reported without repair; update their source manifest through the owning deployment process.

Secrets

Secret Purpose
K8S_MASTER_URL HTTPS API URL reachable by Kestra.
K8S_TOKEN Worker bearer token with the permissions above.
K8S_CA_CERT_DATA Base64-encoded PEM CA bundle for API TLS verification.
SLACK_WEBHOOK_URL Read by secret('SLACK_WEBHOOK_URL') for failure alerts.

Inputs

Input Default Purpose
k8s_master_url, k8s_token, k8s_ca_cert_data Secrets above Worker connection with certificate verification.
target_namespace production Exactly one namespace.
service_name, deployment_name web Explicit Service and Deployment mapping.
reader_service_account selector-reader Read-only in-cluster API identity.
max_objects 100 Per-kind inventory ceiling, 10 to 500; a truncated list fails.
max_replicas 10 Eligible replica ceiling, 1 to 20; zero never qualifies.
verify_seconds 60 Endpoint and HTTP recovery deadline, 5 to 180 seconds.
expected_status 200 Required direct HTTP success status, 200 to 299.
probe_path / Endpoint on the Service's sole port.
reader_image, sidecar_image Pinned Python 3.13 and BusyBox 1.36 images Inspection and Kestra file transfer.
dry_run, auto_remediate true, false Both must permit a write before approval is offered.

Quick start

  1. Import the flow, configure the secrets and create the worker and read-only ServiceAccounts with the permissions above.
  2. Choose a Service and Deployment in one namespace. Confirm their ownership, then annotate the Service with kestra.io/selector-repair-deployment=<deployment_name>. Leave manifest-managed Services under their own controller.
  3. Run with the safe defaults and explicit target inputs. Read inspect's verdict and plan.json; confirm the proposed Deployment selector identifies the intended backend.
  4. Set auto_remediate=true and dry_run=false for an eligible target. Review the saved plan and approve the Pause. A changed target fails before patching.
  5. Require successful prove_traffic output. Run again to confirm the already-correct selector still serves traffic. Keep the schedule disabled until namespace permissions and the chosen probe path are reviewed.

How to extend

Use a dedicated HTTP health path that exercises a dependency required by callers. For a manifest-managed Service, apply the equivalent selector change to its source through the existing release process, then use the read-only verification path.

Limits: one Service and one stable Deployment per execution; no matchExpressions, headless, external, multi-port, dual-stack or non-HTTP Services. Flow concurrency queues executions of this flow only. The Service patch is conditional and atomic; Kubernetes cannot atomically lock the Deployment and Service together, so a workload change after the final read can still occur. Verification fails if identities or protected state change. Writes have no automatic retry. If patching succeeds but verification fails or the execution is interrupted, the selector remains in place and the next run re-reads it and probes traffic without another patch. No automatic rollback restores the broken selector; retain plan.json and use a fresh UID/resourceVersion-conditional patch if an operator chooses rollback. A successful namespace-local probe does not prove ingress, NetworkPolicy paths from other clients or every backend response.

Links

This blueprint was created by zkasuran.

See How

New to Kestra?

Use blueprints to kickstart your first workflows.