id: terramate-stack-drift-and-change-detection-gate
namespace: company.infrastructure
inputs:
- id: git_repository_url
type: STRING
displayName: Infrastructure Repository URL
defaults: "https://github.com/terramate-io/terramate-quickstart-aws"
description: HTTPS URL of the Git repository hosting Terramate, Terraform, or
OpenTofu stacks. The default is the official Terramate quickstart
repository, which contains real multi-stack Terraform configurations.
- id: git_branch
type: STRING
displayName: Git Branch or Ref
defaults: "main"
description: Target branch, commit SHA, or pull request head to clone and audit.
- id: base_branch
type: STRING
displayName: Base Comparison Branch
defaults: "origin/main"
description: Base Git ref used by Terramate change detection to determine
modified stacks.
- id: stacks_directory
type: STRING
displayName: Stacks Root Directory
defaults: "stacks/terraform"
description: Relative directory path containing Terramate stack definitions
(`stack.tm.hcl`).
- id: audit_mode
type: SELECT
displayName: Audit Execution Mode
defaults: "DRIFT_AND_CHANGE_DETECTION"
values:
- "DRIFT_AND_CHANGE_DETECTION"
- "CHANGE_DETECTION_ONLY"
- "DEPENDENCY_DAG_VALIDATION_ONLY"
description: Mode of operation for auditing drift against live infrastructure
versus validating pull request changes.
- id: halt_on_drift
type: BOOL
displayName: Halt Execution on Unmanaged Drift
defaults: true
description: When true, any detected drift across active stacks raises a
critical execution failure to block deployment.
- id: slack_channel
type: STRING
displayName: Slack Notification Channel
defaults: "#platform-infrastructure-alerts"
description: Destination Slack channel for infrastructure drift notifications
and approval gate summaries.
triggers:
- id: infrastructure_pr_webhook
type: io.kestra.plugin.core.trigger.Webhook
description: Triggered via GitHub or GitLab webhook when pull requests touch
Terraform or Terramate configurations.
key: "{{ secret('INFRASTRUCTURE_WEBHOOK_KEY') }}"
disabled: true
- id: nightly_stack_drift_schedule
type: io.kestra.plugin.core.trigger.Schedule
description: Scheduled nightly scan across all infrastructure stacks to detect
unmanaged configuration drift.
cron: "0 4 * * *"
disabled: true
tasks:
- id: prepare_working_directory
type: io.kestra.plugin.core.flow.WorkingDirectory
tasks:
- id: clone_infrastructure_repo
type: io.kestra.plugin.git.Clone
description: Clones the target infrastructure repository with full commit
history for change detection.
url: "{{ inputs.git_repository_url }}"
branch: "{{ inputs.git_branch }}"
- id: audit_terramate_stacks
type: io.kestra.plugin.scripts.shell.Commands
description: Executes Terramate to validate stack dependency graphs, detect
changed stacks, and identify configuration drift.
containerImage: alpine:3.20
taskRunner:
type: io.kestra.plugin.scripts.runner.docker.Docker
env:
STACKS_DIR: "{{ inputs.stacks_directory }}"
BASE_BRANCH: "{{ inputs.base_branch }}"
AUDIT_MODE: "{{ inputs.audit_mode }}"
HALT_ON_DRIFT: "{{ inputs.halt_on_drift }}"
GITHUB_TOKEN: "{{ secret('GITHUB_TOKEN') }}"
beforeCommands:
- apk add --no-cache git curl tar unzip bash python3 py3-pip
- curl -sLo /tmp/terramate.tar.gz
https://github.com/terramate-io/terramate/releases/download/v0.11.3/terramate_0.11.3_linux_x86_64.tar.gz
- tar -xzf /tmp/terramate.tar.gz -C /usr/local/bin terramate && chmod
+x /usr/local/bin/terramate
- curl -sLo /tmp/terraform.zip
https://releases.hashicorp.com/terraform/1.16.6/terraform_1.16.6_linux_amd64.zip
- unzip -oq /tmp/terraform.zip -d /usr/local/bin && chmod +x
/usr/local/bin/terraform
commands:
- python3 audit_terramate.py
inputFiles:
audit_terramate.py: |
import os
import sys
import json
import subprocess
import glob
stacks_dir = os.environ.get("STACKS_DIR", "stacks")
base_branch = os.environ.get("BASE_BRANCH", "origin/main")
audit_mode = os.environ.get("AUDIT_MODE", "DRIFT_AND_CHANGE_DETECTION")
halt_on_drift = os.environ.get("HALT_ON_DRIFT", "true").lower() == "true"
# Step 1: List all stacks under stacks_dir
list_cmd = subprocess.run(["terramate", "--chdir", stacks_dir, "list"], stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True)
all_stacks = [s.strip() for s in list_cmd.stdout.strip().split("\n") if s.strip()]
if not all_stacks:
output_payload = {
"audit_status": "NO_STACKS_FOUND",
"total_stacks_count": 0,
"changed_stacks_count": 0,
"drifted_stacks_count": 0,
"is_syntax_valid": True,
"has_dependency_cycle": False,
"changed_stacks": [],
"plan_check_errors": []
}
print(f"No Terramate stacks found under '{stacks_dir}' in {os.getcwd()}.")
print(f'::{{"outputs": {json.dumps(output_payload)}}}::')
sys.exit(0)
# Step 2: Validate stack formatting and configuration syntax
fmt_cmd = subprocess.run(["terramate", "--chdir", stacks_dir, "fmt", "--check"], stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True)
syntax_clean = (fmt_cmd.returncode == 0)
# Step 3: Change detection against the configured base branch
changed_stacks = []
try:
change_cmd = subprocess.run(
["terramate", "--chdir", stacks_dir, "list", "--changed", "--git-change-base", base_branch],
stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True
)
if change_cmd.returncode == 0:
changed_stacks = [s.strip() for s in change_cmd.stdout.strip().split("\n") if s.strip()]
except Exception:
changed_stacks = []
# Step 4: Validate dependency cycle detection via dry-run execution order
run_order_cmd = subprocess.run(
["terramate", "--chdir", stacks_dir, "run", "--dry-run", "--", "true"],
stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True
)
cycle_detected = (run_order_cmd.returncode != 0 and "cycle" in run_order_cmd.stderr.lower())
# Step 5: Drift detection via `terraform plan -detailed-exitcode` per stack.
# Exit code 0 = no drift, 1 = plan error (missing credentials/backend), 2 = drift present.
drifted_stacks = []
plan_check_errors = []
if audit_mode == "DRIFT_AND_CHANGE_DETECTION" and not cycle_detected:
for stack in all_stacks:
stack_path = os.path.join(stacks_dir, stack) if not stack.startswith(stacks_dir) else stack
plan_cmd = subprocess.run(
["terramate", "--chdir", stack_path, "run", "--", "terraform", "plan", "-detailed-exitcode", "-input=false", "-lock=false"],
stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True
)
if plan_cmd.returncode == 2:
drifted_stacks.append(stack)
elif plan_cmd.returncode not in (0, 2):
plan_check_errors.append({"stack": stack, "error": plan_cmd.stderr.strip()[-500:]})
# Evaluate and determine status
if cycle_detected:
audit_status = "CIRCULAR_DEPENDENCY_ERROR"
elif drifted_stacks and halt_on_drift:
audit_status = "UNEXPECTED_DRIFT_DETECTED"
elif plan_check_errors:
audit_status = "DRIFT_CHECK_INCONCLUSIVE"
elif changed_stacks:
audit_status = "CHANGED_STACKS_REQUIRING_APPROVAL"
else:
audit_status = "ALL_STACKS_SYNCHRONIZED"
report = [
f"# Terramate Infrastructure Stack Audit",
f"- **Audit Status**: `{audit_status}`",
f"- **Total Stacks Discovered**: {len(all_stacks)}",
f"- **Changed Stacks (PR Blast Radius)**: {len(changed_stacks)}",
f"- **Drifted Stacks**: {len(drifted_stacks)}",
f"- **Plan Check Errors**: {len(plan_check_errors)}",
f"- **HCL Syntax Valid**: {syntax_clean}",
f"- **Circular Dependency Safe**: {not cycle_detected}",
"",
"## Discovered Stacks (Topological DAG Order)",
]
for s in all_stacks:
tag = " [DRIFTED]" if s in drifted_stacks else (" [MODIFIED]" if s in changed_stacks else " [SYNCED]")
report.append(f"- `{s}`{tag}")
report_md = "\n".join(report)
print(report_md)
output_payload = {
"audit_status": audit_status,
"total_stacks_count": len(all_stacks),
"changed_stacks_count": len(changed_stacks),
"drifted_stacks_count": len(drifted_stacks),
"is_syntax_valid": syntax_clean,
"has_dependency_cycle": cycle_detected,
"changed_stacks": changed_stacks,
"plan_check_errors": plan_check_errors
}
print(f'::{{"outputs": {json.dumps(output_payload)}}}::')
- id: route_governance_decision
type: io.kestra.plugin.core.flow.Switch
description: Evaluates Terramate audit findings to gate infrastructure
promotion, alert Slack on drift, or confirm compliance.
value: "{{ outputs.audit_terramate_stacks.vars.audit_status }}"
cases:
"CIRCULAR_DEPENDENCY_ERROR":
- id: alert_cycle_error_slack
type: io.kestra.plugin.slack.notifications.SlackIncomingWebhook
description: Dispatches high-severity alert to Slack detailing circular
dependency locks between infrastructure stacks.
url: "{{ secret('SLACK_WEBHOOK_URL') }}"
payload: |
{
"channel": "{{ inputs.slack_channel }}",
"text": ":rotating_light: *Terramate Gate Failure: Circular Stack Dependency Detected* :rotating_light:\n*Repository:* {{ inputs.git_repository_url }} (branch `{{ inputs.git_branch }}`)\n*Error:* Terramate detected a circular dependency cycle in stack configuration.\n*Action:* Inspect `stack.tm.hcl` files for mutually recursive `after` or `before` references."
}
- id: halt_on_dependency_cycle
type: io.kestra.plugin.core.execution.Fail
description: Halts workflow execution to prevent deadlock or out-of-order
resource provisioning.
errorMessage: "CRITICAL: Circular dependency cycle detected in Terramate stack
configurations."
"UNEXPECTED_DRIFT_DETECTED":
- id: alert_drift_slack
type: io.kestra.plugin.slack.notifications.SlackIncomingWebhook
description: Alerts platform engineering in Slack when unmanaged infrastructure
drift is discovered across stacks.
url: "{{ secret('SLACK_WEBHOOK_URL') }}"
payload: |
{
"channel": "{{ inputs.slack_channel }}",
"text": ":warning: *Terramate Drift Warning: Unmanaged Cloud Drift Detected* :warning:\n*Repository:* {{ inputs.git_repository_url }}\n*Drifted Stacks:* {{ outputs.audit_terramate_stacks.vars.drifted_stacks_count }}\n*Action:* Run `terramate run -- terraform plan` to review out-of-band infrastructure modifications."
}
- id: halt_on_unmanaged_drift
type: io.kestra.plugin.core.execution.Fail
description: Fails execution when unmanaged drift violates deployment compliance
policies.
errorMessage: "FAILED: Infrastructure state has drifted from Git definitions
across managed stacks."
"CHANGED_STACKS_REQUIRING_APPROVAL":
- id: notify_changed_stacks_slack
type: io.kestra.plugin.slack.notifications.SlackIncomingWebhook
description: Posts blast-radius summary to Slack listing specific stacks
modified by the pull request.
url: "{{ secret('SLACK_WEBHOOK_URL') }}"
payload: |
{
"channel": "{{ inputs.slack_channel }}",
"text": ":white_check_mark: *Terramate Change Detection: {{ outputs.audit_terramate_stacks.vars.changed_stacks_count }} Stacks Impacted* :white_check_mark:\n*Repository:* {{ inputs.git_repository_url }} (branch `{{ inputs.git_branch }}`)\n*Impacted Stacks:* {{ outputs.audit_terramate_stacks.vars.changed_stacks | join(', ') }}\n*Status:* Changes verified in topological order and pending pull request review."
}
"DRIFT_CHECK_INCONCLUSIVE":
- id: alert_drift_check_inconclusive_slack
type: io.kestra.plugin.slack.notifications.SlackIncomingWebhook
description: Alerts the team when terraform plan failed on one or more stacks,
so drift status could not be determined.
url: "{{ secret('SLACK_WEBHOOK_URL') }}"
payload: |
{
"channel": "{{ inputs.slack_channel }}",
"text": ":warning: *Terramate Drift Check Inconclusive* :warning:\n*Repository:* {{ inputs.git_repository_url }} (branch `{{ inputs.git_branch }}`)\n*Action:* `terraform plan` failed on one or more stacks (missing backend credentials or state access). Drift status is unknown; this is not the same as a clean audit. Check `plan_check_errors` in the execution output for details."
}
- id: halt_on_inconclusive_drift_check
type: io.kestra.plugin.core.execution.Fail
description: Halts execution since drift status could not be verified; treating
an inconclusive check as a pass would be unsafe.
errorMessage: "FAILED: Drift check could not run on one or more stacks;
terraform plan errored. See plan_check_errors for details."
"NO_STACKS_FOUND":
- id: log_no_stacks_found
type: io.kestra.plugin.core.log.Log
description: Records that no Terramate stacks were discovered under the
configured stacks_directory.
message: "Terramate audit: no stacks found under '{{ inputs.stacks_directory }}'
in {{ inputs.git_repository_url }} (branch {{ inputs.git_branch }}).
Nothing was audited."
defaults:
- id: log_clean_synchronization
type: io.kestra.plugin.core.log.Log
description: Logs certification confirming all infrastructure stacks are
formatted, synchronized, and free of drift.
message: "Terramate audit passed: All {{
outputs.audit_terramate_stacks.vars.total_stacks_count }}
infrastructure stacks are in clean synchronization with zero detected
drift."