id: terraform-plan-drift-detect
namespace: company.team
description: |
Triage Terraform drift the moment a scheduled plan reports it, instead of
letting newly detected changes pile up until the next deploy. A CI job that
runs `terraform show -json` POSTs the plan document to a keyed webhook, the
flow stages that plan as a deterministic fixture when none has landed,
Python walks the resource changes for update and replace actions and collects
the changed attribute paths, and an If escalates only when real drift exists.
Drift alerts Slack with the changed resources and can fail the run, a clean
plan is logged, and the verdict plus the drifted resources are published as
outputs.
triggers:
- id: on_plan_ready
type: io.kestra.plugin.core.trigger.Webhook
description: The drift detection pipeline POSTs the terraform show -json
document here right after each scheduled plan, so triage starts while the
changes are still fresh.
key: "{{ secret('TERRAFORM_PLAN_WEBHOOK_KEY') }}"
- id: daily_drift_sweep
type: io.kestra.plugin.core.trigger.Schedule
description: Daily 05:00 UTC net that rescores the staged plan document, shipped
disabled until the webhook path is trusted in your environment.
cron: "0 5 * * *"
disabled: true
inputs:
- id: plan_path
type: STRING
defaults: tfplan.json
description: Path of the terraform show -json document inside the working
directory, the file the webhook body is written to or the bundled fixture
is staged at.
- id: workspace_name
type: STRING
defaults: prod-networking
description: Terraform workspace the plan was produced for, echoed in the drift
alert so multi workspace estates stay distinguishable.
- id: fail_on_drift
type: BOOL
defaults: true
description: Whether detected drift turns the execution red after the Slack
alert, flip to false for report only runs.
tasks:
# --- 1. plan workspace ---
- id: plan_workspace
type: io.kestra.plugin.core.flow.WorkingDirectory
description: One shared directory so the staged plan document and the drift
parser read the same file for the whole run.
tasks:
# --- 2. plan fixture ---
- id: stage_plan_output
type: io.kestra.plugin.scripts.shell.Commands
description: Write a terraform show -json fixture with a heredoc, two managed
resources where one carries a drifted bucket acl and the other is a
clean no-op, so the parser always has a plan to read when no CI job
has posted.
taskRunner:
type: io.kestra.plugin.scripts.runner.docker.Docker
entryPoint: []
containerImage: alpine:3.20
env:
PLAN_PATH: "{{ inputs.plan_path }}"
commands:
- |
set -u
cat > tfplan.json <<'JSON'
{
"format_version": "1.2",
"terraform_version": "1.9.5",
"resource_changes": [
{
"address": "aws_s3_bucket.audit_logs",
"mode": "managed",
"type": "aws_s3_bucket",
"name": "audit_logs",
"change": {
"actions": ["update"],
"before": {"acl": "private", "force_destroy": false, "versioning": [{"enabled": true}]},
"after": {"acl": "public-read", "force_destroy": false, "versioning": [{"enabled": true}]}
}
},
{
"address": "aws_security_group.edge",
"mode": "managed",
"type": "aws_security_group",
"name": "edge",
"change": {
"actions": ["no-op"],
"before": {"ingress": [{"from_port": 443, "to_port": 443}]},
"after": {"ingress": [{"from_port": 443, "to_port": 443}]}
}
}
]
}
JSON
if [ "${PLAN_PATH}" != "tfplan.json" ]; then
cp tfplan.json "${PLAN_PATH}" 2>/dev/null || true
echo "copied fixture to ${PLAN_PATH}"
fi
echo "staged $(wc -c < tfplan.json) bytes of plan json"
# --- 3. drift parse ---
- id: parse_plan
type: io.kestra.plugin.scripts.python.Script
description: Walk every resource change, treat update and replace actions as
drift, collect the attribute paths whose before and after values
differ, and emit the verdict, the drifted resources and the flattened
changed paths through the outputs protocol.
containerImage: python:3.12-slim
env:
PLAN_PATH: "{{ inputs.plan_path }}"
script: |
import json
import os
DRIFT_ACTIONS = {"update", "replace"}
plan_path = (os.environ.get("PLAN_PATH") or "").strip() or "tfplan.json"
outputs = {
"plan_ok": False,
"has_drift": False,
"drifted_count": 0,
"drifted_resources": [],
"changed_attributes": [],
}
def load_plan(path):
if not os.path.exists(path) or os.path.getsize(path) == 0:
return None
try:
with open(path, "r", encoding="utf-8") as handle:
return json.load(handle)
except ValueError:
return None
def diff_keys(before, after, prefix=""):
changed = []
if isinstance(before, dict) and isinstance(after, dict):
for key in sorted(set(before) | set(after)):
path = prefix + "." + key if prefix else key
if key not in before or key not in after:
changed.append(path)
else:
changed.extend(diff_keys(before[key], after[key], path))
elif isinstance(before, list) and isinstance(after, list):
if before != after:
changed.append((prefix or "root") + "[]")
else:
if before != after:
changed.append(prefix or "root")
return changed
plan = load_plan(plan_path)
if plan is not None:
changes = plan.get("resource_changes")
if not isinstance(changes, list):
changes = []
drifted = []
flat_paths = []
for change in changes:
if not isinstance(change, dict):
continue
inner = change.get("change")
if not isinstance(inner, dict):
continue
actions = inner.get("actions")
if not isinstance(actions, list):
continue
if not DRIFT_ACTIONS.intersection({str(a) for a in actions}):
continue
address = str(change.get("address") or "unknown")
paths = diff_keys(inner.get("before"), inner.get("after"))
drifted.append({
"address": address,
"actions": [str(a) for a in actions],
"changed_attributes": paths,
})
flat_paths.extend(address + "." + p for p in paths)
outputs.update({
"plan_ok": True,
"has_drift": bool(drifted),
"drifted_count": len(drifted),
"drifted_resources": drifted,
"changed_attributes": sorted(set(flat_paths)),
})
print("plan_ok=%s drifted=%d attributes=%d" % (
outputs["plan_ok"], outputs["drifted_count"], len(outputs["changed_attributes"])))
print("::" + json.dumps({"outputs": outputs}) + "::")
# --- 4. drift gate ---
- id: drift_gate
type: io.kestra.plugin.core.flow.If
description: Branch on a parseable plan that actually drifted, so alerts and
failure fire only when update or replace actions were found.
condition: "{{ outputs.parse_plan.vars.plan_ok and
outputs.parse_plan.vars.has_drift }}"
then:
# --- 5. drift escalation ---
- id: alert_drift
type: io.kestra.plugin.slack.notifications.SlackIncomingWebhook
description: Post the workspace, the drifted resource count and the changed
attribute paths so the owning team can reconcile before the next
deploy.
url: "{{ secret('SLACK_WEBHOOK_URL') }}"
payload: |
{
"text": "Terraform drift detected in workspace {{ inputs.workspace_name }} - {{ outputs.parse_plan.vars.drifted_count }} resource(s) changed out of band. Changed attributes: {{ outputs.parse_plan.vars.changed_attributes | join(', ') }}. Reconcile state or update configuration before the next deploy. Execution {{ execution.id }}."
}
- id: enforce_gate
type: io.kestra.plugin.core.flow.If
description: Apply the fail_on_drift policy, turning the run red for gating
pipelines and staying report only when the input is flipped off.
condition: "{{ inputs.fail_on_drift }}"
then:
- id: fail_execution
type: io.kestra.plugin.core.execution.Fail
description: Fail the execution so the pipeline watching this gate stops instead
of deploying on top of drifted infrastructure.
errorMessage: "Terraform drift detected in {{ inputs.workspace_name }} across {{
outputs.parse_plan.vars.drifted_count }} resource(s)."
else:
- id: log_gate_softened
type: io.kestra.plugin.core.log.Log
description: Record that drift was found but the fail on drift policy is off,
keeping the run green for report only estates.
message: "Terraform drift in {{ inputs.workspace_name }} across {{
outputs.parse_plan.vars.drifted_count }} resource(s) not enforced
- fail_on_drift is false, alert sent only."
else:
- id: log_no_drift
type: io.kestra.plugin.core.log.Log
description: Record the clean or unparseable outcome so a quiet plan still
leaves evidence the triage ran.
message: "Terraform plan triage for {{ inputs.workspace_name }} found no drift -
plan_ok {{ outputs.parse_plan.vars.plan_ok }}, {{
outputs.parse_plan.vars.drifted_count }} drifted resource(s)."
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: has_drift
type: BOOL
description: True when at least one resource change carried an update or replace
action, false for clean or unparseable plans.
value: "{{ outputs.parse_plan.vars.has_drift }}"
- id: drifted_count
type: INT
description: Number of resources whose change actions indicate drift in the
scored plan, for example 1 when only the bucket acl moved.
value: "{{ outputs.parse_plan.vars.drifted_count }}"
- id: drifted_resources
type: ARRAY
description: Drifted resources with their address, actions and changed attribute
paths, for example the audit logs bucket with its acl.
value: "{{ outputs.parse_plan.vars.drifted_resources }}"
- id: changed_attributes
type: ARRAY
description: Flattened attribute paths that differ between the before and after
state across every drifted resource, prefixed with the resource address.
value: "{{ outputs.parse_plan.vars.changed_attributes }}"