id: vercel-deploy-preview-gate
namespace: company.team
description: |
Turn every git push into a gated Vercel preview: create the
deployment pinned to the pushed commit, poll until Vercel settles,
and fail the run with a GitHub issue and a Slack notice when the
build errors or overruns its time budget.
triggers:
- id: on_push
type: io.kestra.plugin.core.trigger.Webhook
description: Your git host or CI POSTs the push payload here to start a preview
deployment. Shipped with a keyed URL, treat the key as a secret.
key: "{{ secret('PREVIEW_DEPLOY_WEBHOOK_KEY') }}"
- id: nightly_replay
type: io.kestra.plugin.core.trigger.Schedule
description: Optional nightly re-check of the preview pipeline. Ships disabled,
enable it once the webhook is wired.
cron: "0 4 * * *"
disabled: true
inputs:
- id: project_name
type: STRING
defaults: your-vercel-project
description: Vercel project the preview deployment is created for, exactly as it
appears in the Vercel dashboard.
- id: repository
type: STRING
defaults: your-org/your-repo
description: GitHub repository in owner/repo form, used when the push payload is
empty and as the target for the issue the gate opens.
- id: budget_seconds
type: INT
defaults: 300
description: Build time budget in seconds. A READY deployment that took longer
than this fails the gate, and 0 disables the budget check.
tasks:
# --- 1. collect ---
- id: parse_push_payload
type: io.kestra.plugin.scripts.python.Script
description: Pull repository, branch, commit SHA, and actor out of the push
payload, falling back to flow inputs so a manual run still works.
containerImage: python:3.12-slim
inputFiles:
push.json: "{{ trigger.body is defined ? (trigger.body | toJson) : '{}' }}"
repo_fallback.txt: "{{ inputs.repository }}"
script: |
import json
def read_text(path):
try:
with open(path) as fh:
return fh.read().strip()
except Exception:
return ""
def load_payload(path):
raw = read_text(path)
if not raw:
return {}
try:
data = json.loads(raw)
except Exception:
return {}
if isinstance(data, str):
try:
data = json.loads(data)
except Exception:
return {}
return data if isinstance(data, dict) else {}
def pick(payload, *paths, default=""):
for path in paths:
cur = payload
for part in path.split("."):
if isinstance(cur, dict) and part in cur:
cur = cur[part]
else:
cur = None
break
if cur is None or isinstance(cur, (dict, list)):
continue
text = str(cur).strip()
if text:
return text
return default
payload = load_payload("push.json")
repo = pick(payload, "repository.full_name", "repo.full_name",
"repository.name", "repo.name", "repository", "repo")
if not repo:
repo = read_text("repo_fallback.txt")
if not repo:
repo = "your-org/your-repo"
ref = pick(payload, "ref", "branch", "ref_name")
branch = ref
if branch.startswith("refs/heads/"):
branch = branch[len("refs/heads/"):]
if not branch:
branch = "main"
commit_sha = pick(payload, "after", "head_commit.id", "commit",
"sha", "commit_id", "revision")
actor = pick(payload, "pusher.name", "sender.login", "actor",
"pusher", "user.login", "username")
if not actor:
actor = "unknown"
if "/" in repo:
repo_owner, _, repo_name = repo.partition("/")
else:
repo_owner, repo_name = repo, repo
print("repo=%s branch=%s sha=%s actor=%s" % (repo, branch, commit_sha, actor))
print("::" + json.dumps({"outputs": {
"repo": repo,
"repo_owner": repo_owner,
"repo_name": repo_name,
"branch": branch,
"commit_sha": commit_sha,
"actor": actor,
}}) + "::")
# --- 2. deploy ---
- id: create_deployment
type: io.kestra.plugin.core.http.Request
description: Create a preview deployment pinned to the pushed commit, so the
preview URL always belongs to the exact SHA under review.
method: POST
uri: "https://api.vercel.com/v13/deployments"
contentType: application/json
headers:
Authorization: "Bearer {{ secret('VERCEL_TOKEN') }}"
body: |
{
"name": "{{ inputs.project_name }}",
"target": "preview",
"gitSource": {
"type": "github",
"org": "{{ outputs.parse_push_payload.vars.repo_owner }}",
"repo": "{{ outputs.parse_push_payload.vars.repo_name }}",
"ref": "{{ outputs.parse_push_payload.vars.branch }}"{% if outputs.parse_push_payload.vars.commit_sha != '' %},
"sha": "{{ outputs.parse_push_payload.vars.commit_sha }}"{% endif %}
},
"meta": {
"githubCommitRef": "{{ outputs.parse_push_payload.vars.branch }}"{% if outputs.parse_push_payload.vars.commit_sha != '' %},
"githubCommitSha": "{{ outputs.parse_push_payload.vars.commit_sha }}"{% endif %}
}
}
# --- 3. wait ---
- id: wait_until_ready
type: io.kestra.plugin.core.flow.LoopUntil
description: Poll the deployment every 10 seconds for at most 30 checks, about 5
minutes, and stop as soon as Vercel reports READY or ERROR.
condition: "{{ (outputs.poll_deployment.body | jq('.readyState') | first) ==
'READY' or (outputs.poll_deployment.body | jq('.readyState') | first) ==
'ERROR' }}"
failOnMaxReached: false
checkFrequency:
interval: PT10S
maxIterations: 30
tasks:
- id: poll_deployment
type: io.kestra.plugin.core.http.Request
description: Read the current ready state, URL, and build duration for the
deployment that was just created.
method: GET
uri: "https://api.vercel.com/v13/deployments/{{ outputs.create_deployment.body |
jq('(.uid // .id)') | first }}"
headers:
Authorization: "Bearer {{ secret('VERCEL_TOKEN') }}"
# --- 4. assess ---
- id: assess
type: io.kestra.plugin.scripts.python.Script
description: Turn the settled deployment into a pass or fail verdict with
reasons covering ready state, build duration against the budget, and the
preview URL.
containerImage: python:3.12-slim
inputFiles:
deployment.json: "{{ outputs.poll_deployment.body ?? '{}' }}"
create.json: "{{ outputs.create_deployment.body ?? '{}' }}"
budget.txt: "{{ inputs.budget_seconds }}"
repo.txt: "{{ outputs.parse_push_payload.vars.repo }}"
branch.txt: "{{ outputs.parse_push_payload.vars.branch }}"
commit_sha.txt: "{{ outputs.parse_push_payload.vars.commit_sha }}"
actor.txt: "{{ outputs.parse_push_payload.vars.actor }}"
script: |
import json
def read_text(path, default=""):
try:
with open(path) as fh:
return fh.read().strip()
except Exception:
return default
def load_json(path, default):
raw = read_text(path)
if not raw:
return default
try:
data = json.loads(raw)
except Exception:
return default
if isinstance(data, str):
try:
data = json.loads(data)
except Exception:
return default
return data
def as_text(value, default=""):
if value is None:
return default
if isinstance(value, (dict, list)):
return default
text = str(value).strip()
return text if text else default
deployment = load_json("deployment.json", {})
if not isinstance(deployment, dict):
deployment = {}
created = load_json("create.json", {})
if not isinstance(created, dict):
created = {}
state = as_text(deployment.get("readyState")) or as_text(created.get("readyState"))
error_message = as_text(deployment.get("errorMessage")) or as_text(created.get("errorMessage"))
url = as_text(deployment.get("url")) or as_text(created.get("url"))
if url and not url.startswith("http"):
url = "https://" + url
https_url = url
deployment_id = (as_text(deployment.get("uid")) or as_text(deployment.get("id"))
or as_text(created.get("uid")) or as_text(created.get("id")))
try:
budget = int(read_text("budget.txt", "0"))
except Exception:
budget = 0
if budget < 0:
budget = 0
ms = None
duration = deployment.get("duration")
if isinstance(duration, dict) and isinstance(duration.get("timeToReady"), (int, float)):
ms = float(duration["timeToReady"])
else:
created_at = deployment.get("createdAt") or deployment.get("created") or created.get("createdAt") or created.get("created")
ready_at = deployment.get("ready")
if isinstance(created_at, (int, float)) and isinstance(ready_at, (int, float)) and ready_at >= created_at:
ms = float(ready_at) - float(created_at)
build_seconds = int(round(ms / 1000.0)) if ms and ms > 0 else 0
repo = read_text("repo.txt", "unknown")
branch = read_text("branch.txt", "main")
commit_sha = read_text("commit_sha.txt", "unknown")
actor = read_text("actor.txt", "unknown")
reasons = []
if not state:
reasons.append("Vercel reported no readyState for this deployment")
elif state == "ERROR":
text = "deployment failed with readyState ERROR"
if error_message:
text = text + ": " + error_message
reasons.append(text)
elif state != "READY":
reasons.append("deployment was still " + state + " when the 30-check poll bound was reached")
if budget > 0 and build_seconds > budget:
reasons.append("build took " + str(build_seconds) + "s, over the " + str(budget) + "s budget")
if not https_url:
reasons.append("Vercel returned no deployment url")
verdict = "pass" if not reasons else "fail"
reasons_summary = "; ".join(reasons) if reasons else "none"
settled = state in ("READY", "ERROR")
checks = {
"state_ok": state == "READY",
"budget_ok": (budget <= 0) or (build_seconds <= budget),
"url_ok": bool(https_url),
"settled": settled,
}
print("verdict=%s state=%s build_seconds=%s budget=%s reasons=%d" % (
verdict, state or "none", build_seconds, budget, len(reasons)))
print("::" + json.dumps({"outputs": {
"verdict": verdict,
"reasons": reasons,
"reasons_summary": reasons_summary,
"state": state,
"https_url": https_url,
"deployment_id": deployment_id,
"build_seconds": build_seconds,
"budget_seconds": budget,
"poll_bound_reached": not settled,
"checks": checks,
"repo": repo,
"branch": branch,
"commit_sha": commit_sha,
"actor": actor,
}}) + "::")
# --- 5. gate ---
- id: gate
type: io.kestra.plugin.core.flow.If
description: A failed verdict escalates as a GitHub issue, a Slack notice, and a
red execution. A clean preview just records itself.
condition: "{{ outputs.assess.vars.verdict == 'fail' }}"
then:
- id: open_issue
type: io.kestra.plugin.github.issues.Create
description: Open a labeled GitHub issue carrying the preview URL and every
reason the gate failed, so triage lands in the same backlog engineers
already work from.
jwtToken: "{{ secret('GITHUB_TOKEN') }}"
repository: "{{ outputs.assess.vars.repo }}"
title: "Preview deploy gate failed for {{ outputs.assess.vars.repo }} ({{
outputs.assess.vars.branch }})"
body: |
## Preview deployment failed
**Repository** {{ outputs.assess.vars.repo }}, branch `{{ outputs.assess.vars.branch }}`, commit `{{ outputs.assess.vars.commit_sha }}`.
**Preview** {{ outputs.assess.vars.https_url }}
**Deployment id** {{ outputs.assess.vars.deployment_id }}
**State** {{ outputs.assess.vars.state }}
**Build** {{ outputs.assess.vars.build_seconds }}s of {{ outputs.assess.vars.budget_seconds }}s budget
**Pushed by** {{ outputs.assess.vars.actor }}
**Reasons**
{{ outputs.assess.vars.reasons_summary }}
Execution: {{ execution.id }}
Fix the build or raise the budget, push again, then close this issue once the preview is green.
labels:
- preview-deploy
- vercel
- id: alert_slack
type: io.kestra.plugin.slack.notifications.SlackIncomingWebhook
description: Tell the team which repository missed the gate, why, and where the
waiting GitHub issue is.
url: "{{ secret('SLACK_WEBHOOK_URL') }}"
payload: |
{
"text": "Vercel preview gate FAILED for {{ outputs.assess.vars.repo }} ({{ outputs.assess.vars.branch }} at {{ outputs.assess.vars.commit_sha }}): {{ outputs.assess.vars.reasons_summary }}. Preview {{ outputs.assess.vars.https_url }}, build {{ outputs.assess.vars.build_seconds }}s of {{ outputs.assess.vars.budget_seconds }}s budget. A GitHub issue has been opened. Execution {{ execution.id }}."
}
- id: fail_the_run
type: io.kestra.plugin.core.execution.Fail
description: Fail the execution so whatever pipeline watches this gate sees red
instead of a quiet success.
errorMessage: "Preview deploy gate failed for {{ outputs.assess.vars.repo }}: {{
outputs.assess.vars.reasons_summary }}."
else:
- id: log_preview
type: io.kestra.plugin.core.log.Log
description: Record the healthy preview so the execution history doubles as a
deploy trail.
message: "Preview READY at {{ outputs.assess.vars.https_url }} (build {{
outputs.assess.vars.build_seconds }}s of {{
outputs.assess.vars.budget_seconds }}s budget) for {{
outputs.assess.vars.repo }} branch {{ outputs.assess.vars.branch }} at
{{ outputs.assess.vars.commit_sha }}, pushed by {{
outputs.assess.vars.actor }}."
errors:
- id: alert_failure
type: io.kestra.plugin.slack.notifications.SlackIncomingWebhook
description: Alert when the gate itself cannot run, because a silent gate is
indistinguishable from a healthy preview.
url: "{{ secret('SLACK_WEBHOOK_URL') }}"
payload: |
{
"text": "Vercel preview gate FAILED in flow {{ flow.id }} (execution {{ execution.id }}). The preview was NOT assessed. Verify the VERCEL_TOKEN and GITHUB_TOKEN secrets and the webhook key."
}
outputs:
- id: deployment_url
type: STRING
description: HTTPS URL of the preview deployment that was gated.
value: "{{ outputs.assess.vars.https_url }}"
- id: state
type: STRING
description: Final Vercel ready state, for example READY or ERROR.
value: "{{ outputs.assess.vars.state }}"
- id: build_seconds
type: INT
description: Build duration in seconds as reported by Vercel, 0 when the API did
not report one.
value: "{{ outputs.assess.vars.build_seconds }}"
- id: verdict
type: STRING
description: Gate result, either pass or fail.
value: "{{ outputs.assess.vars.verdict }}"
- id: reasons
type: JSON
description: Structured list of the reasons a failed verdict was returned, empty
for a pass.
value: "{{ outputs.assess.vars.reasons | toJson }}"