id: namespace-governance-drift-guard
namespace: company.team
description: |
Scan a Kestra namespace against governance policy - required labels, id
conventions, descriptions - and when drift is found, export the namespace to
a governance branch, open a pull request carrying the violations manifest,
and notify Slack, so convention drift always lands as a reviewable ticket
instead of silently accumulating.
triggers:
- id: weekly_governance_scan
type: io.kestra.plugin.core.trigger.Schedule
description: Weekly governance sweep (enable by flipping disabled).
cron: "0 7 * * 1"
disabled: true
- id: on_demand_scan
type: io.kestra.plugin.core.trigger.Webhook
description: On-demand scan, e.g. after onboarding a new team or before an audit.
key: "{{ secret('WEBHOOK_KEY') }}"
inputs:
- id: namespace_prefix
type: STRING
displayName: Namespace prefix
description: Every flow under this prefix is scanned.
defaults: company
- id: policy
type: JSON
displayName: Governance policy
description: Required labels, id pattern, and whether a description is mandatory.
defaults: |
{"required_labels": ["environment", "owner"], "id_pattern": "^[a-z0-9-]+$", "require_description": true}
- id: kestra_url
type: STRING
displayName: Kestra API URL
description: Reachable from the worker; localhost works in standalone setups.
defaults: http://localhost:8080
- id: repository
type: STRING
displayName: Git repository
description: GitHub repository (full URL) that receives the governance export.
defaults: https://github.com/my-org/kestra-flows
- id: pr_repository
type: STRING
displayName: Pull request repository
description: owner/repo form used by the GitHub pull request task.
defaults: my-org/kestra-flows
- id: branch
type: STRING
displayName: Governance branch
description: Branch that PushFlows writes; repeat runs update the same branch and PR.
defaults: governance-drift-report
- id: fail_on_violations
type: BOOL
displayName: Fail on violations
description: End the run as FAILED after the PR is opened, so the scan shows red
in schedules.
defaults: true
tasks:
- id: scan_and_evaluate
type: io.kestra.plugin.scripts.python.Script
description: Page through the Kestra flows API and evaluate every flow against
the governance policy.
env:
KESTRA_URL: "{{ inputs.kestra_url }}"
NAMESPACE_PREFIX: "{{ inputs.namespace_prefix }}"
POLICY_JSON: "{{ inputs.policy | toJson }}"
KESTRA_USERNAME: "{{ secret('KESTRA_USERNAME') }}"
KESTRA_PASSWORD: "{{ secret('KESTRA_PASSWORD') }}"
EXECUTION_ID: "{{ execution.id }}"
script: |
import base64
import json
import os
import re
import urllib.parse
import urllib.request
def label_keys(flow):
labels = flow.get("labels")
keys = set()
if isinstance(labels, dict):
keys.update(str(k) for k in labels.keys())
elif isinstance(labels, list):
for entry in labels:
if isinstance(entry, dict) and entry.get("key") is not None:
keys.add(str(entry.get("key")))
elif isinstance(entry, (list, tuple)) and entry:
keys.add(str(entry[0]))
return keys
def evaluate(flow, policy):
issues = []
flow_id = str(flow.get("id") or "").strip()
if not flow_id:
issues.append("missing flow id")
if policy.get("require_description", True) and not str(flow.get("description") or "").strip():
issues.append("missing description")
pattern = policy.get("id_pattern")
if pattern and flow_id:
try:
if not re.match(pattern, flow_id):
issues.append("id does not match " + pattern)
except re.error:
issues.append("policy id_pattern is not a valid regex")
missing = [k for k in (policy.get("required_labels") or []) if k not in label_keys(flow)]
if missing:
issues.append("missing labels: " + ", ".join(missing))
return issues
def fetch_flows(base_url, username, password, namespace_prefix, max_pages=50):
flows = []
token = base64.b64encode(
"{}:{}".format(username, password).encode("utf-8")
).decode("ascii")
for page in range(1, max_pages + 1):
query = urllib.parse.urlencode({
"page": page,
"size": 200,
"filters[namespace][STARTS_WITH]": namespace_prefix,
})
url = "{}/api/v1/main/flows/search?{}".format(base_url.rstrip("/"), query)
request = urllib.request.Request(url, headers={"Authorization": "Basic " + token})
with urllib.request.urlopen(request, timeout=30) as response:
payload = json.loads(response.read().decode("utf-8") or "{}")
batch = payload.get("results") if isinstance(payload, dict) else payload
if not isinstance(batch, list) or not batch:
break
flows.extend(item for item in batch if isinstance(item, dict))
total = payload.get("total") if isinstance(payload, dict) else None
if isinstance(total, int) and len(flows) >= total:
break
if len(batch) < 200:
break
return flows
def build_report(violations):
rows = ["| Flow | Issues |", "|---|---|"]
for row in violations[:20]:
rows.append("| {} | {} |".format(row["flow"], "; ".join(row["issues"])))
if len(violations) > 20:
rows.append("| ... and {} more | full list in execution outputs |".format(len(violations) - 20))
return "\n".join(rows)
def main():
policy = json.loads(os.environ.get("POLICY_JSON") or "{}")
flows = fetch_flows(
os.environ.get("KESTRA_URL") or "http://localhost:8080",
os.environ.get("KESTRA_USERNAME") or "",
os.environ.get("KESTRA_PASSWORD") or "",
os.environ.get("NAMESPACE_PREFIX") or "company",
)
violations = []
for flow in flows:
issues = evaluate(flow, policy)
if issues:
violations.append({
"flow": "{}.{}".format(flow.get("namespace") or "?", flow.get("id") or "?"),
"issues": issues,
})
rows = build_report(violations)
print("checked {} flows, {} in violation".format(len(flows), len(violations)))
print(
"::"
+ json.dumps(
{
"outputs": {
"violations": violations,
"violation_count": len(violations),
"checked_count": len(flows),
"compliant_count": len(flows) - len(violations),
"report_markdown": rows,
}
}
)
+ "::"
)
if __name__ == "__main__":
main()
- id: drift_gate
type: io.kestra.plugin.core.flow.If
description: Only export and open a pull request when the policy actually found drift.
condition: "{{ outputs.scan_and_evaluate.vars.violation_count > 0 }}"
then:
- id: export_namespace
type: io.kestra.plugin.git.PushFlows
description: Export every flow in the namespace to the governance branch for review.
branch: "{{ inputs.branch }}"
sourceNamespace: "{{ inputs.namespace_prefix }}"
targetNamespace: "{{ inputs.namespace_prefix }}"
flows: "*"
gitDirectory: _flows
url: "{{ inputs.repository }}"
username: "{{ secret('GITHUB_USERNAME') }}"
password: "{{ secret('GITHUB_ACCESS_TOKEN') }}"
commitMessage: "Governance scan {{ execution.id }} - {{
outputs.scan_and_evaluate.vars.violation_count }} flow(s) in
violation"
- id: open_pull_request
type: io.kestra.plugin.github.pulls.Create
description: Open the pull request that carries the violations manifest for
maintainers.
sourceBranch: "{{ inputs.branch }}"
targetBranch: main
repository: "{{ inputs.pr_repository }}"
oauthToken: "{{ secret('GITHUB_ACCESS_TOKEN') }}"
title: "Governance drift: {{ outputs.scan_and_evaluate.vars.violation_count }}
of {{ outputs.scan_and_evaluate.vars.checked_count }} flow(s) violate
policy"
body: |
## Namespace governance scan
{{ outputs.scan_and_evaluate.vars.report_markdown }}
- Checked: {{ outputs.scan_and_evaluate.vars.checked_count }}
- Compliant: {{ outputs.scan_and_evaluate.vars.compliant_count }}
- Violations: {{ outputs.scan_and_evaluate.vars.violation_count }}
- Execution: {{ execution.id }}
- Policy: `{{ inputs.policy | toJson }}`
- id: announce_drift
type: io.kestra.plugin.slack.notifications.SlackIncomingWebhook
description: Post the drift summary and the pull request link to Slack.
url: "{{ secret('SLACK_WEBHOOK_URL') }}"
messageText: |
*Namespace governance drift found* ({{ execution.id }})
• {{ outputs.scan_and_evaluate.vars.violation_count }} of {{ outputs.scan_and_evaluate.vars.checked_count }} flow(s) violate policy under `{{ inputs.namespace_prefix }}`.
• Pull request: {{ outputs.open_pull_request.pullRequestUrl }}
• Fix the flows on `{{ inputs.branch }}` or update the policy input if the rule itself changed.
else:
- id: log_compliant
type: io.kestra.plugin.core.log.Log
description: Nothing to do when every flow already satisfies the policy.
message: "Governance scan clean - {{
outputs.scan_and_evaluate.vars.checked_count }} flow(s) checked under
{{ inputs.namespace_prefix }}, zero violations."
- id: fail_gate
type: io.kestra.plugin.core.flow.If
description: Turn violations into a red execution after the PR is filed, when
configured to fail.
condition: "{{ outputs.scan_and_evaluate.vars.violation_count > 0 and
inputs.fail_on_violations }}"
then:
- id: stop_on_drift
type: io.kestra.plugin.core.execution.Fail
description: Fail the run so scheduled governance scans show up in failure alerts.
errorMessage: "Governance drift: {{
outputs.scan_and_evaluate.vars.violation_count }} flow(s) in violation
- pull request opened on branch {{ inputs.branch }}."
outputs:
- id: violation_count
type: INT
description: Flows with at least one policy violation.
value: "{{ outputs.scan_and_evaluate.vars.violation_count }}"
- id: checked_count
type: INT
description: Flows scanned under the namespace prefix.
value: "{{ outputs.scan_and_evaluate.vars.checked_count }}"
- id: violations
type: JSON
description: Per-flow list of governance issues found.
value: "{{ outputs.scan_and_evaluate.vars.violations }}"
- id: report_markdown
type: STRING
description: Markdown violations table embedded in the pull request.
value: "{{ outputs.scan_and_evaluate.vars.report_markdown }}"
- id: pull_request_url
type: STRING
description: Governance pull request URL when drift was found.
value: "{{ outputs.open_pull_request is defined ?
outputs.open_pull_request.pullRequestUrl : 'no-drift' }}"
errors:
- id: alert_on_failure
type: io.kestra.plugin.slack.notifications.SlackIncomingWebhook
description: Alert when the scan itself breaks so an API outage is not mistaken
for compliance.
url: "{{ secret('SLACK_WEBHOOK_URL') }}"
messageText: "namespace-governance-drift-guard ERRORED in flow {{ flow.id }}
(execution {{ execution.id }}) - the scan did not complete; do not read
silence as compliance. Check execution logs."