id: mattermost-incident-bridge
namespace: company.team
description: |
Bridges incident management into Mattermost so every status change lands in
the team channel with the right severity tag and the right follow-up. A
webhook accepts an incident event of incident_id, severity, status and
summary, a shell step writes the tracked state file from a heredoc and a
python step applies the change to the opened, acknowledged, resolved
lifecycle, counts the incidents still open and builds the channel payload
that a core HTTP task posts to a Mattermost incoming webhook. When the event
is a sev1 or sev2 that just opened, a loop pages every on-call target through
a second webhook, a GitHub issue is filed and sev1 pages also reach the
on-call mailbox; quieter events are recorded with a log line instead. The
run exposes the verdict, whether a channel message was posted, the severity
and the open incident count as typed outputs.
triggers:
- id: incident_status_change
type: io.kestra.plugin.core.trigger.Webhook
description: The incident tool POSTs one event of incident_id, severity, status
and summary whenever an incident opens, is acknowledged or is resolved.
key: "{{ secret('INCIDENT_WEBHOOK_KEY') }}"
- id: daily_state_reconcile
type: io.kestra.plugin.core.trigger.Schedule
description: Disabled 06:00 net that would replay the bridge against the state
file each morning until someone switches it on.
cron: "0 6 * * *"
disabled: true
inputs:
- id: channel
type: STRING
defaults: incidents
description: Mattermost channel name the bridge posts its severity-tagged note
into, without the leading hash.
- id: page_targets
type: STRING
defaults: primary-oncall,secondary-oncall
description: Comma separated on-call targets the loop walks when a sev1 or sev2
opens and must be paged.
- id: oncall_email
type: STRING
defaults: oncall@example.com
description: Mailbox that receives the extra email escalation when the opened
incident is a sev1.
tasks:
# --- 1. the state file and the bridge verdict ---
- id: workspace
type: io.kestra.plugin.core.flow.WorkingDirectory
description: One shared directory so the state file written by the shell step is
the exact file the bridge step reads and updates.
tasks:
- id: write_incident_state
type: io.kestra.plugin.scripts.shell.Commands
description: Writes incident-state.json from a heredoc of three tracked
incidents, one opened, one acknowledged and one resolved, so the open
count is measured against real history.
commands:
- |
cat > incident-state.json <<'INCIDENT_STATE_EOF'
{
"incidents": [
{"incident_id": "INC-1041", "severity": "sev2", "status": "opened", "summary": "Checkout API 5xx spike in eu-west-1"},
{"incident_id": "INC-1038", "severity": "sev3", "status": "acknowledged", "summary": "Search index lag on the catalog cluster"},
{"incident_id": "INC-1022", "severity": "sev1", "status": "resolved", "summary": "Primary database failover completed"}
]
}
INCIDENT_STATE_EOF
cat incident-state.json
- id: bridge_incident
type: io.kestra.plugin.scripts.python.Script
description: Applies the incoming status change to the state file, walks the
opened to acknowledged to resolved lifecycle, builds the
severity-tagged channel payload and prints one outputs marker line
with the verdict, the posted flag, the severity and the open count.
taskRunner:
type: io.kestra.plugin.core.runner.Process
env:
INCIDENT_ID: "{{ trigger is not defined ? '' : ((trigger.body ?? {}).incident_id
?? '') }}"
SEVERITY: "{{ trigger is not defined ? '' : ((trigger.body ?? {}).severity ??
'') }}"
STATUS: "{{ trigger is not defined ? '' : ((trigger.body ?? {}).status ?? '')
}}"
SUMMARY: "{{ trigger is not defined ? '' : ((trigger.body ?? {}).summary ?? '')
}}"
CHANNEL: "{{ inputs.channel }}"
EXECUTION_ID: "{{ execution.id }}"
script: |
import json
import os
STATE_FILE = "incident-state.json"
SEVERITIES = ("sev1", "sev2", "sev3", "sev4")
STATUSES = ("opened", "acknowledged", "resolved")
OPEN_STATUSES = ("opened", "acknowledged")
PAGE_SEVERITIES = ("sev1", "sev2")
MARKS = {
"sev1": ":red_circle:",
"sev2": ":large_orange_circle:",
"sev3": ":large_yellow_circle:",
"sev4": ":large_blue_circle:",
}
incident_id = os.environ.get("INCIDENT_ID", "").strip()
severity = os.environ.get("SEVERITY", "").strip().lower()
status = os.environ.get("STATUS", "").strip().lower()
summary = os.environ.get("SUMMARY", "").strip()
channel = os.environ.get("CHANNEL", "incidents").strip().lstrip("#") or "incidents"
execution_id = os.environ.get("EXECUTION_ID", "").strip()
state = {}
if os.path.exists(STATE_FILE):
try:
with open(STATE_FILE, encoding="utf-8") as handle:
state = json.load(handle)
except ValueError:
state = {}
entries = state.get("incidents") if isinstance(state, dict) else None
if not isinstance(entries, list):
entries = []
entries = [e for e in entries
if isinstance(e, dict) and (e.get("incident_id") or "").strip()]
known = None
for entry in entries:
if (entry.get("incident_id") or "").strip() == incident_id:
known = entry
break
previous = (known.get("status") or "").strip().lower() if known else ""
valid = bool(incident_id) and severity in SEVERITIES and status in STATUSES
if valid:
if known is None:
tracked = entries + [{
"incident_id": incident_id,
"severity": severity,
"status": status,
"summary": summary,
}]
transition = "new->" + status
else:
merged = dict(known)
merged["status"] = status
merged["severity"] = severity
if summary:
merged["summary"] = summary
tracked = [merged if (e.get("incident_id") or "").strip() == incident_id
else e for e in entries]
transition = (previous or "unknown") + "->" + status
else:
tracked = entries
transition = "unknown->unknown"
open_incidents = sum(
1 for e in tracked
if (e.get("status") or "").strip().lower() in OPEN_STATUSES)
if valid:
channel_posted = True
note = " transition " + transition
if status == "resolved":
verdict = "RESOLVED_ARCHIVED"
note += "; archive note, incident closed and dropped from the open count"
elif status == "acknowledged":
verdict = "ACKNOWLEDGED"
elif severity in PAGE_SEVERITIES:
verdict = "PAGE_ESCALATED"
note += "; on-call page and issue follow"
else:
verdict = "CHANNEL_NOTIFIED"
text = "%s [%s] %s %s - %s | #%s |%s | %d open incident(s)" % (
MARKS[severity], severity.upper(), incident_id, status,
summary or "no summary supplied", channel, note, open_incidents)
else:
channel_posted = False
verdict = "INVALID_PAYLOAD"
text = ":warning: Incident bridge got an unrecognized event (id=%s severity=%s status=%s), nothing was paged." % (
incident_id or "missing", severity or "missing", status or "missing")
if execution_id:
text = text + " Execution " + execution_id + "."
channel_payload = {"channel": "#" + channel, "text": text}
print(text)
print("::" + json.dumps({"outputs": {"verdict": verdict, "channel_posted": channel_posted, "severity": severity or "unknown", "open_incidents": open_incidents, "channel_payload": channel_payload}}, ensure_ascii=True) + "::")
# --- 2. the channel note ---
- id: post_channel_message
type: io.kestra.plugin.core.http.Request
description: POSTs the python built payload to the Mattermost incoming webhook
so the channel always sees the severity-tagged lifecycle note for this
event.
method: POST
uri: "{{ secret('MATTERMOST_WEBHOOK_URL') }}"
headers:
Content-Type: application/json
body: "{{ outputs.bridge_incident.vars.channel_payload | toJson }}"
# --- 3. the page gate ---
- id: escalation_gate
type: io.kestra.plugin.core.flow.If
description: Pages and tickets only when the event is a sev1 or sev2 that just
opened, so acknowledgements, resolutions and lower severities stay
channel-only.
condition: "{{ outputs.bridge_incident.vars.severity in ['sev1', 'sev2'] and
outputs.bridge_incident.vars.verdict == 'PAGE_ESCALATED' }}"
then:
- id: page_oncall
type: io.kestra.plugin.core.flow.Loop
description: Walks the page_targets one at a time so each on-call rotation
member gets the page for this opening incident in order.
values: "{{ inputs.page_targets.split(',') }}"
concurrencyLimit: 1
tasks:
- id: send_page
type: io.kestra.plugin.core.http.Request
description: POSTs a rotating light page for this incident to the second
Mattermost incoming webhook wired to the on-call rotation.
method: POST
uri: "{{ secret('MATTERMOST_PAGE_WEBHOOK_URL') }}"
headers:
Content-Type: application/json
body: |
{"channel": "{{ item.value }}", "text": ":rotating_light: PAGE {{ outputs.bridge_incident.vars.severity | upper }} {{ trigger is not defined ? 'incident' : ((trigger.body ?? {}).incident_id ?? 'incident') }} opened - {{ trigger is not defined ? 'see the bridge post in the channel' : ((trigger.body ?? {}).summary ?? 'see the bridge post in the channel') }}. Acknowledge in the incident tool now."}
- id: open_incident_issue
type: io.kestra.plugin.github.issues.Create
description: Files a labeled ticket for the opened sev1 or sev2 so the page has
an owner and an audit trail outside the chat channel.
oauthToken: "{{ secret('GITHUB_TOKEN') }}"
repository: your-org/on-call
title: "[{{ outputs.bridge_incident.vars.severity | upper }}] {{ trigger is not
defined ? 'Incident' : ((trigger.body ?? {}).incident_id ??
'Incident') }} opened"
body: |
## Incident page
Severity **{{ outputs.bridge_incident.vars.severity | upper }}** incident
**{{ trigger is not defined ? 'Incident' : ((trigger.body ?? {}).incident_id ?? 'Incident') }}**
opened in the bridge. Summary from the incident tool, as posted to the channel.
{{ trigger is not defined ? 'No summary was supplied with the event.' : ((trigger.body ?? {}).summary ?? 'No summary was supplied with the event.') }}
Channel note posted, {{ outputs.bridge_incident.vars.open_incidents }} incident(s) open after this event.
Execution {{ execution.id }}.
labels:
- incident
- oncall
- id: sev1_email_gate
type: io.kestra.plugin.core.flow.If
description: Sends the mailbox escalation only for sev1 pages, where a chat page
and a ticket alone are not enough coverage.
condition: "{{ outputs.bridge_incident.vars.severity == 'sev1' }}"
then:
- id: email_oncall
type: io.kestra.plugin.email.MailSend
description: Emails the on-call mailbox the incident id, severity and summary so
a sev1 reaches someone who has not opened Mattermost.
from: "{{ secret('SMTP_FROM') }}"
to: "{{ inputs.oncall_email }}"
host: "{{ secret('SMTP_HOST') }}"
username: "{{ secret('SMTP_USERNAME') }}"
password: "{{ secret('SMTP_PASSWORD') }}"
port: 465
subject: "SEV1 page - {{ trigger is not defined ? 'Incident' : ((trigger.body ??
{}).incident_id ?? 'Incident') }} opened"
htmlTextContent: |
<p>A <strong>SEV1</strong> incident just opened and the bridge paged the on-call rotation.</p>
<p><strong>Incident</strong> {{ trigger is not defined ? 'Incident' : ((trigger.body ?? {}).incident_id ?? 'Incident') }}</p>
<p><strong>Summary</strong> {{ trigger is not defined ? 'No summary was supplied with the event.' : ((trigger.body ?? {}).summary ?? 'No summary was supplied with the event.') }}</p>
<p>{{ outputs.bridge_incident.vars.open_incidents }} incident(s) are open after this event. Acknowledge in the incident tool now.</p>
<p>Execution {{ execution.id }}</p>
else:
- id: log_sev2_no_email
type: io.kestra.plugin.core.log.Log
description: Records that a sev2 was paged in chat and ticketed without the sev1
mailbox escalation.
message: "Sev2 {{ trigger is not defined ? 'incident' : ((trigger.body ??
{}).incident_id ?? 'incident') }} paged to {{ inputs.page_targets
}} and ticketed, mailbox escalation skipped for sev1 only."
else:
- id: log_no_page
type: io.kestra.plugin.core.log.Log
description: Records the quiet outcome for acknowledgements, resolutions and
lower severities, which need a channel note but no page.
message: "No page for {{ outputs.bridge_incident.vars.severity }} {{
outputs.bridge_incident.vars.verdict }}, {{
outputs.bridge_incident.vars.open_incidents }} incident(s) open after
this event."
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: verdict
type: STRING
value: "{{ outputs.bridge_incident.vars.verdict }}"
- id: channel_posted
type: BOOL
value: "{{ outputs.bridge_incident.vars.channel_posted }}"
- id: severity
type: STRING
value: "{{ outputs.bridge_incident.vars.severity }}"
- id: open_incidents
type: INT
value: "{{ outputs.bridge_incident.vars.open_incidents }}"