id: crossplane-composition-drift-claim-gate
namespace: company.team
description: |
Crossplane claims drift from composition intent through late-initialized fields and failed polls while still surface-reading Ready, and no deploy gate looks at claim health. A keyed webhook accepts the claim status report with its conditions and managed resources, a Python pass classifies the claim as Ready, NotReady or Unavailable and extracts every drift marker, and a Switch routes on that state. NotReady claims get a Slack alert and a labeled GitHub issue, Unavailable claims get a Slack alert, and the final gate fails the execution whenever the claim is not Ready, with the claim name, state, drift markers and resource counts published as outputs while unexpected failures escalate to Slack.
triggers:
- id: post_claim_status
type: io.kestra.plugin.core.trigger.Webhook
description: POST the claim status report here after each reconcile, for example
from a cluster job that reads the claim, its conditions and its composed
resources.
key: "{{ secret('CLAIM_STATUS_WEBHOOK_KEY') }}"
- id: hourly_claim_safety_net
type: io.kestra.plugin.core.trigger.Schedule
description: Hourly 07:00 UTC safety net, shipped disabled so no claim is paged
until an operator reviews the classification inputs and switches it on.
cron: "0 7 * * *"
disabled: true
inputs:
- id: claim_namespace
type: STRING
defaults: team-a
description: Namespace recorded in the alert when the posted claim metadata does
not carry one, so messages still name where the claim lives.
- id: condition_stale_hours
type: INT
defaults: 24
description: Hours a non Ready claim may sit in the same condition before the
classifier adds a staleness note to the detail text.
- id: require_all_resources_ready
type: BOOL
defaults: true
description: Whether a composed resource that is not Ready blocks a claim that
itself reports Ready.
tasks:
# --- 1. claim status analysis ---
- id: inspect_claim_status
type: io.kestra.plugin.scripts.python.Script
description: Read the posted claim status, classify it from the Ready condition
plus the composed resources, collect drift markers, and emit the state
through the outputs protocol.
taskRunner:
type: io.kestra.plugin.scripts.runner.docker.Docker
containerImage: python:3.12-slim
inputFiles:
claim_status.json: "{{ (trigger.body ?? {}) | toJson }}"
env:
CLAIM_NAMESPACE: "{{ inputs.claim_namespace }}"
CONDITION_STALE_HOURS: "{{ inputs.condition_stale_hours }}"
REQUIRE_ALL_RESOURCES_READY: "{{ inputs.require_all_resources_ready }}"
script: |
import json
import os
from datetime import datetime, timezone
REPORT_FILE = "claim_status.json"
def env_float(name, default):
try:
return float(os.environ.get(name, default))
except (TypeError, ValueError):
return float(default)
def env_bool(name, default):
return str(os.environ.get(name, default)).strip().lower() in ("1", "true", "yes", "on")
CLAIM_NAMESPACE = os.environ.get("CLAIM_NAMESPACE", "team-a")
CONDITION_STALE_HOURS = env_float("CONDITION_STALE_HOURS", 24)
REQUIRE_ALL_RESOURCES_READY = env_bool("REQUIRE_ALL_RESOURCES_READY", "true")
def parse_timestamp(value):
if not value:
return None
text = str(value).strip()
if text.endswith("Z"):
text = text[:-1] + "+00:00"
try:
stamp = datetime.fromisoformat(text)
except ValueError:
return None
if stamp.tzinfo is None:
stamp = stamp.replace(tzinfo=timezone.utc)
return stamp.astimezone(timezone.utc)
def load_report(path):
try:
if not os.path.exists(path) or os.path.getsize(path) == 0:
return None, "claim report file is missing or empty"
with open(path, "r", encoding="utf-8") as handle:
document = json.load(handle)
document = json.loads(document) if isinstance(document, str) else document
if not isinstance(document, dict):
return None, "claim report is not a JSON object"
return document, ""
except ValueError:
return None, "claim report is not valid JSON"
report, problem = load_report(REPORT_FILE)
now = parse_timestamp(report.get("observedAt")) if report else None
now = now or datetime.now(timezone.utc)
claim_name, composition = "unknown-claim", "unknown-composition"
claim_state, detail = "Unavailable", problem
markers, blocking = [], []
non_ready, resource_count, condition_age_hours = 0, 0, 0.0
if report is not None:
claim = report.get("claim") or {}
meta = claim.get("metadata") or {}
claim_name = str(meta.get("name") or "unnamed-claim")
namespace = str(meta.get("namespace") or CLAIM_NAMESPACE)
composition = str((report.get("composition") or {}).get("name") or "unnamed-composition")
conditions = [row for row in (report.get("conditions") or []) if isinstance(row, dict)]
ready_status, ready_transition, seen = "", None, []
for condition in conditions:
ctype = str(condition.get("type") or "unknown")
cstatus = str(condition.get("status") or "unknown")
seen.append("%s=%s" % (ctype, cstatus))
if ctype == "Ready":
ready_status = cstatus
ready_transition = parse_timestamp(condition.get("lastTransitionTime"))
condition_age_hours = round((now - ready_transition).total_seconds() / 3600.0, 1) if ready_transition else 0.0
resources = [row for row in (report.get("resources") or []) if isinstance(row, dict)]
resource_count = len(resources)
for resource in resources:
rname = str(resource.get("name") or "unnamed-resource")
rstatus = str(resource.get("ready") or "unknown")
late = sorted({str(field) for field in (resource.get("lateInitializedFields") or []) if field})
if rstatus.lower() != "true":
non_ready += 1
markers.append("%s not Ready (%s)" % (rname, rstatus))
if REQUIRE_ALL_RESOURCES_READY:
blocking.append("%s not Ready" % rname)
if late:
text = "%s late-initialized %s" % (rname, ", ".join(late))
markers.append(text)
blocking.append(text)
if report.get("driftDetected"):
markers.append("composition reconciler reports spec drift")
blocking.append("composition reconciler reports spec drift")
if ready_status in ("", "unknown", "Unknown"):
claim_state = "Unavailable"
detail = "claim %s has no Ready condition (observed %s)" % (claim_name, ", ".join(seen) or "none")
elif ready_status == "False":
claim_state = "NotReady"
detail = "claim %s is NotReady - %s" % (claim_name, "; ".join(blocking) or "Ready condition is False")
elif blocking:
claim_state = "NotReady"
detail = "claim %s reports Ready while composition intent drifted - %s" % (claim_name, "; ".join(blocking))
else:
claim_state = "Ready"
detail = "claim %s in %s is Ready on composition %s with %d resource(s) and no drift markers" % (
claim_name, namespace, composition, resource_count)
if claim_state != "Ready" and condition_age_hours > CONDITION_STALE_HOURS:
detail += "; Ready condition unchanged for %.1fh past the %.0fh policy" % (
condition_age_hours, CONDITION_STALE_HOURS)
gate_blocked = claim_state != "Ready"
print("state=%s claim=%s composition=%s resources=%d non_ready=%d markers=%d" % (
claim_state, claim_name, composition, resource_count, non_ready, len(markers)))
print("::" + json.dumps({"outputs": {
"claim_name": claim_name,
"claim_state": claim_state,
"gate_blocked": gate_blocked,
"composition": composition,
"drift_markers": markers,
"non_ready_resources": non_ready,
"condition_age_hours": condition_age_hours,
"detail": detail,
}}) + "::")
# --- 2. state routing ---
- id: route_on_claim_state
type: io.kestra.plugin.core.flow.Switch
description: Route on the classified claim state, so each state gets exactly the
escalation it deserves instead of one generic claim alert.
value: "{{ outputs.inspect_claim_status.vars.claim_state }}"
cases:
Ready:
- id: log_ready_claim
type: io.kestra.plugin.core.log.Log
description: Record the healthy claim with its composition and resource count so
the execution history still proves which claim was inspected.
message: "Crossplane claim {{ outputs.inspect_claim_status.vars.claim_name }} is
Ready - composition {{ outputs.inspect_claim_status.vars.composition
}}, {{ outputs.inspect_claim_status.vars.non_ready_resources }}
resource(s) not ready, no drift markers."
NotReady:
- id: alert_not_ready
type: io.kestra.plugin.slack.notifications.SlackIncomingWebhook
description: Post the claim name, composition and every drift marker to the
platform channel the moment the claim stops matching composition
intent.
url: "{{ secret('SLACK_WEBHOOK_URL') }}"
payload: |
{"text": "Crossplane claim {{ outputs.inspect_claim_status.vars.claim_name }} is NotReady. {{ outputs.inspect_claim_status.vars.detail }}. Execution {{ execution.id }}."}
- id: open_claim_issue
type: io.kestra.plugin.github.issues.Create
description: Open a labeled GitHub issue carrying the drift markers, so claim
repair gets an owner and a thread instead of a channel message that
scrolls away.
oauthToken: "{{ secret('GITHUB_TOKEN') }}"
repository: your-org/platform-claims
title: "Crossplane claim {{ outputs.inspect_claim_status.vars.claim_name }}
drifted from composition intent"
body: |
## Claim drift detected
Claim **{{ outputs.inspect_claim_status.vars.claim_name }}** on composition
**{{ outputs.inspect_claim_status.vars.composition }}** classified
**{{ outputs.inspect_claim_status.vars.claim_state }}** with
{{ outputs.inspect_claim_status.vars.non_ready_resources }} resource(s) not ready.
{{ outputs.inspect_claim_status.vars.detail }}
Execution `{{ execution.id }}`.
```json
{{ outputs.inspect_claim_status.vars.drift_markers | toJson }}
```
labels:
- crossplane
- drift
Unavailable:
- id: alert_unavailable
type: io.kestra.plugin.slack.notifications.SlackIncomingWebhook
description: Raise an Unavailable claim loudly, because a claim with no Ready
condition is usually a broken composition or a broken connection
secret.
url: "{{ secret('SLACK_WEBHOOK_URL') }}"
payload: |
{"text": "Crossplane claim {{ outputs.inspect_claim_status.vars.claim_name }} is Unavailable. {{ outputs.inspect_claim_status.vars.detail }}. Composition {{ outputs.inspect_claim_status.vars.composition }}. Execution {{ execution.id }}."}
defaults:
- id: log_unexpected_state
type: io.kestra.plugin.core.log.Log
description: Catch any state string the classifier did not predict, so a future
condition type cannot slip past the gate silently.
message: "Unexpected claim state {{
outputs.inspect_claim_status.vars.claim_state }} for claim {{
outputs.inspect_claim_status.vars.claim_name }}."
# --- 3. gate verdict ---
- id: claim_gate
type: io.kestra.plugin.core.flow.If
description: Fail the execution whenever the claim is not Ready, so a promotion
pipeline waiting on claim health stops instead of building on a drifted
claim.
condition: "{{ outputs.inspect_claim_status.vars.gate_blocked }}"
then:
- id: alert_gate_blocked
type: io.kestra.plugin.slack.notifications.SlackIncomingWebhook
description: Announce that the gate is failing the execution, naming the claim,
its state and the drift markers, right before the failure stops the
pipeline.
url: "{{ secret('SLACK_WEBHOOK_URL') }}"
payload: |
{"text": "Crossplane claim gate BLOCKED for {{ flow.id }}. {{ outputs.inspect_claim_status.vars.detail }}. Markers {{ outputs.inspect_claim_status.vars.drift_markers | toJson }}. Execution {{ execution.id }}."}
- id: fail_claim_gate
type: io.kestra.plugin.core.execution.Fail
description: Fail with the classifier detail in the error message, naming the
exact drift without opening a second channel.
errorMessage: "Claim gate blocked - {{ outputs.inspect_claim_status.vars.detail }}"
else:
- id: log_gate_passed
type: io.kestra.plugin.core.log.Log
description: Record the passing verdict with the claim name and composition so
the execution history proves gate health.
message: "Claim gate passed - {{ outputs.inspect_claim_status.vars.claim_name }}
on {{ outputs.inspect_claim_status.vars.composition }} is Ready with
no drift markers."
errors:
- id: notify_failure
type: io.kestra.plugin.slack.notifications.SlackIncomingWebhook
description: Escalate any failure to the ops channel with the execution url.
url: "{{ secret('SLACK_WEBHOOK_URL') }}"
payload: |
{"text": "FAILED: {{ flow.id }} {{ execution.id }}"}
outputs:
- id: claim_name
type: STRING
value: "{{ outputs.inspect_claim_status.vars.claim_name }}"
- id: claim_state
type: STRING
value: "{{ outputs.inspect_claim_status.vars.claim_state }}"
- id: gate_blocked
type: BOOL
value: "{{ outputs.inspect_claim_status.vars.gate_blocked }}"
- id: composition
type: STRING
value: "{{ outputs.inspect_claim_status.vars.composition }}"
- id: drift_markers
type: ARRAY
value: "{{ outputs.inspect_claim_status.vars.drift_markers | toJson }}"
- id: non_ready_resources
type: INT
value: "{{ outputs.inspect_claim_status.vars.non_ready_resources }}"
- id: detail
type: STRING
value: "{{ outputs.inspect_claim_status.vars.detail }}"