id: atlantis-stale-workspace-lock-and-deadlock-reconciler
namespace: company.platform
inputs:
- id: atlantis_url
type: STRING
displayName: Atlantis Server URL
required: true
description: Base HTTP or HTTPS URL of the Atlantis server, without a trailing
slash (for example http://localhost:4141).
- id: github_repository
type: STRING
displayName: GitHub Repository
required: true
description: Target GitHub repository in 'owner/repo' format managing the
Terraform configurations.
- id: stale_lock_hours
type: INT
displayName: Stale Lock Inactivity Threshold (Hours)
defaults: 48
description: Hours without activity on an open pull request before the Atlantis
lock it holds is flagged as stale.
- id: auto_unlock_orphans
type: BOOL
displayName: Automatically Release Orphaned Locks
defaults: false
description: When true, calls the Atlantis DELETE /locks endpoint to release
locks held by closed or merged pull requests. When false, orphaned locks
are only reported.
- id: slack_channel
type: STRING
displayName: Slack Notification Channel
defaults: "#devops-infra"
description: Slack channel destination for lock release audit logs and stale
workspace deadlock warnings.
tasks:
- id: fetch_atlantis_locks
type: io.kestra.plugin.core.http.Request
description: Lists every lock held on the Atlantis server through its GET
/api/locks endpoint.
uri: "{{ inputs.atlantis_url }}/api/locks"
method: GET
options:
auth:
type: BASIC
username: "{{ secret('ATLANTIS_WEB_USERNAME') }}"
password: "{{ secret('ATLANTIS_WEB_PASSWORD') }}"
headers:
Accept: "application/json"
retry:
type: constant
interval: PT5S
maxAttempts: 3
- id: reconcile_locks_with_github
type: io.kestra.plugin.scripts.python.Script
description: Compares each Atlantis lock for the target repository with the live
state of the pull request that holds it.
taskRunner:
type: io.kestra.plugin.scripts.runner.docker.Docker
containerImage: python:3.12-slim
inputFiles:
locks.json: "{{ outputs.fetch_atlantis_locks.body }}"
env:
GITHUB_REPO: "{{ inputs.github_repository }}"
STALE_HOURS: "{{ inputs.stale_lock_hours }}"
GITHUB_TOKEN: "{{ secret('GITHUB_TOKEN') }}"
script: |
import json
import os
import sys
import urllib.error
import urllib.request
from datetime import datetime, timezone
github_repo = os.environ["GITHUB_REPO"].strip()
stale_hours = float(os.environ["STALE_HOURS"])
headers = {
"Accept": "application/vnd.github+json",
"User-Agent": "Kestra-Atlantis-Reconciler",
"Authorization": "Bearer " + os.environ["GITHUB_TOKEN"].strip(),
}
# Atlantis GET /api/locks returns {"Locks": [{"Name", "ProjectName", "ProjectRepo",
# "ProjectRepoPath", "PullID" (string), "PullURL", "User", "Workspace", "Time"}]}
with open("locks.json", "r", encoding="utf-8") as f:
all_locks = json.load(f).get("Locks") or []
def github_get(path):
req = urllib.request.Request("https://api.github.com/repos/" + path, headers=headers)
with urllib.request.urlopen(req, timeout=15) as resp:
return json.loads(resp.read().decode("utf-8"))
# A 404 on a pull request only means "deleted" when the repository itself is readable
# with this token, so verify access first and abort instead of releasing locks blindly.
try:
github_get(github_repo)
except Exception as e:
print(f"Cannot read repository {github_repo} with GITHUB_TOKEN: {e}")
sys.exit(1)
locks_list = [l for l in all_locks if (l.get("ProjectRepo") or "").lower() == github_repo.lower()]
other_repo_count = len(all_locks) - len(locks_list)
orphaned_locks, stale_locks, active_locks, lookup_errors = [], [], [], []
now_utc = datetime.now(timezone.utc)
for lock in locks_list:
entry = {
"lock_id": lock.get("Name", ""),
"project": lock.get("ProjectName") or lock.get("ProjectRepoPath") or "",
"path": lock.get("ProjectRepoPath", ""),
"workspace": lock.get("Workspace", ""),
"pull_num": lock.get("PullID", ""),
"user": lock.get("User", ""),
}
try:
pr = github_get(f"{github_repo}/pulls/{int(entry['pull_num'])}")
except urllib.error.HTTPError as e:
if e.code == 404:
orphaned_locks.append({**entry, "reason": "PR not found"})
else:
lookup_errors.append({**entry, "error": f"HTTP {e.code}"})
continue
except Exception as e:
lookup_errors.append({**entry, "error": str(e)})
continue
if pr.get("state") == "closed" or pr.get("merged"):
orphaned_locks.append({**entry, "reason": "PR merged" if pr.get("merged") else "PR closed"})
continue
updated_at = datetime.fromisoformat(pr["updated_at"].replace("Z", "+00:00"))
idle_hours = round((now_utc - updated_at).total_seconds() / 3600.0, 1)
if idle_hours > stale_hours:
stale_locks.append({**entry, "idle_hours": idle_hours})
else:
active_locks.append(entry)
if lookup_errors:
verdict = "LOOKUP_ERRORS"
elif not locks_list:
verdict = "NO_LOCKS_HELD"
elif orphaned_locks:
verdict = "ORPHANED_LOCKS_DETECTED"
elif stale_locks:
verdict = "STALE_LOCKS_DETECTED"
else:
verdict = "ALL_LOCKS_ACTIVE"
summary = {
"status": verdict,
"total_locks_inspected": len(locks_list),
"other_repo_locks_skipped": other_repo_count,
"orphaned_count": len(orphaned_locks),
"orphaned_locks": orphaned_locks,
"stale_count": len(stale_locks),
"stale_locks": stale_locks,
"active_count": len(active_locks),
"lookup_error_count": len(lookup_errors),
"lookup_errors": lookup_errors,
}
print(f"Reconciliation: {verdict}. Inspected {len(locks_list)} lock(s) for {github_repo} ({other_repo_count} for other repos skipped): {len(orphaned_locks)} orphaned, {len(stale_locks)} stale, {len(active_locks)} active, {len(lookup_errors)} lookup error(s).")
print("::" + json.dumps({"outputs": summary}) + "::")
- id: evaluate_reconciliation_verdict
type: io.kestra.plugin.core.flow.Switch
description: Directs remediation and notification actions according to the lock
reconciliation analysis.
value: "{{ outputs.reconcile_locks_with_github.vars.status }}"
cases:
"ORPHANED_LOCKS_DETECTED":
- id: check_auto_unlock_toggle
type: io.kestra.plugin.core.flow.If
description: Releases orphaned locks only when auto_unlock_orphans is true,
otherwise asks for manual review.
condition: "{{ inputs.auto_unlock_orphans }}"
then:
- id: release_orphaned_locks
type: io.kestra.plugin.core.flow.Loop
description: Issues one DELETE /locks request to Atlantis per orphaned lock.
concurrencyLimit: 1
values: "{{ outputs.reconcile_locks_with_github.vars.orphaned_locks }}"
tasks:
- id: delete_lock_from_atlantis
type: io.kestra.plugin.core.http.Request
description: Calls Atlantis to discard the plan and release the workspace lock.
uri: "{{ inputs.atlantis_url }}/locks?id={{ item.value.lock_id | urlencode }}"
method: DELETE
options:
auth:
type: BASIC
username: "{{ secret('ATLANTIS_WEB_USERNAME') }}"
password: "{{ secret('ATLANTIS_WEB_PASSWORD') }}"
- id: log_lock_release_action
type: io.kestra.plugin.core.log.Log
message: "UNLOCKED: Released lock '{{ item.value.lock_id }}' for project '{{
item.value.project }}' (workspace '{{ item.value.workspace
}}', {{ item.value.reason }}: PR #{{ item.value.pull_num
}})."
- id: alert_orphaned_locks_reclaimed
type: io.kestra.plugin.slack.notifications.SlackIncomingWebhook
description: Posts an audit card to Slack confirming the locks that were
released.
url: "{{ secret('SLACK_WEBHOOK_URL') }}"
payload: |
{
"channel": {{ inputs.slack_channel | toJson }},
"text": "🔓 *Atlantis Terraform Workspace Locks Released*",
"attachments": [
{
"color": "#36A64F",
"fields": [
{"title": "Repository", "value": {{ inputs.github_repository | toJson }}, "short": true},
{"title": "Locks Released", "value": {{ (outputs.reconcile_locks_with_github.vars.orphaned_count | string) | toJson }}, "short": true},
{"title": "Released Locks", "value": {{ (outputs.reconcile_locks_with_github.vars.orphaned_locks | toJson) | toJson }}, "short": false},
{"title": "Execution ID", "value": {{ execution.id | toJson }}, "short": true}
]
}
]
}
else:
- id: alert_orphans_manual_review
type: io.kestra.plugin.slack.notifications.SlackIncomingWebhook
description: Alerts Slack when orphaned locks exist but auto_unlock_orphans is
false.
url: "{{ secret('SLACK_WEBHOOK_URL') }}"
payload: |
{
"channel": {{ inputs.slack_channel | toJson }},
"text": "⚠️ *Orphaned Atlantis Locks Require Manual Release*",
"attachments": [
{
"color": "#FFA500",
"fields": [
{"title": "Repository", "value": {{ inputs.github_repository | toJson }}, "short": true},
{"title": "Orphaned Count", "value": {{ (outputs.reconcile_locks_with_github.vars.orphaned_count | string) | toJson }}, "short": true},
{"title": "Notice", "value": "These locks are held by closed or merged PRs. Set auto_unlock_orphans to true to release them.", "short": false},
{"title": "Orphaned Locks", "value": {{ (outputs.reconcile_locks_with_github.vars.orphaned_locks | toJson) | toJson }}, "short": false}
]
}
]
}
"STALE_LOCKS_DETECTED":
- id: alert_stale_locks_warning
type: io.kestra.plugin.slack.notifications.SlackIncomingWebhook
description: Warns the channel about open pull requests that hold locks past the
inactivity threshold.
url: "{{ secret('SLACK_WEBHOOK_URL') }}"
payload: |
{
"channel": {{ inputs.slack_channel | toJson }},
"text": "⏱️ *Stale Atlantis Workspace Locks Detected*",
"attachments": [
{
"color": "#E24A4A",
"fields": [
{"title": "Repository", "value": {{ inputs.github_repository | toJson }}, "short": true},
{"title": "Stale Count", "value": {{ (outputs.reconcile_locks_with_github.vars.stale_count | string) | toJson }}, "short": true},
{"title": "Threshold", "value": {{ ((inputs.stale_lock_hours | string) ~ " hours") | toJson }}, "short": true},
{"title": "Stale Locks", "value": {{ (outputs.reconcile_locks_with_github.vars.stale_locks | toJson) | toJson }}, "short": false}
]
}
]
}
"LOOKUP_ERRORS":
- id: fail_on_lookup_errors
type: io.kestra.plugin.core.execution.Fail
description: Stops without releasing anything when a pull request state could
not be verified.
errorMessage: "Could not verify {{
outputs.reconcile_locks_with_github.vars.lookup_error_count }} pull
request(s) on GitHub, so no lock was released. Details: {{
outputs.reconcile_locks_with_github.vars.lookup_errors | toJson }}"
"ALL_LOCKS_ACTIVE":
- id: log_all_locks_healthy
type: io.kestra.plugin.core.log.Log
message: "AUDIT CLEAN: All {{
outputs.reconcile_locks_with_github.vars.total_locks_inspected }}
Atlantis lock(s) for {{ inputs.github_repository }} belong to open
pull requests active within {{ inputs.stale_lock_hours }}h."
"NO_LOCKS_HELD":
- id: log_no_locks_held
type: io.kestra.plugin.core.log.Log
message: "AUDIT IDLE: Atlantis holds no locks for {{ inputs.github_repository }}
({{
outputs.reconcile_locks_with_github.vars.other_repo_locks_skipped }}
lock(s) for other repositories ignored)."
defaults:
- id: log_unclassified_status
type: io.kestra.plugin.core.log.Log
message: "Atlantis lock reconciler returned unclassified status: {{
outputs.reconcile_locks_with_github.vars.status }}."