Disk Space Watchdog with Tiered Thresholds and Telegram Alert
Summary
This workflow monitors disk usage on a remote Linux server via SSH, applying tiered thresholds (warning and critical) to avoid alert fatigue. It tracks the last known state of each mount point using n8n's workflow static data, so you only receive a notification when a disk changes level (e.g., from OK to warning, or from critical back to OK). Alerts are sent first to a Telegram chat; if that fails, an email is sent as a reliable fallback. The workflow is fully configurable through environment variables, making it easy to adapt without editing the code.
Step-by-Step Nodes
-
Schedule Trigger (No auth) — Runs the workflow every 30 minutes. Configured via
intervalrule with minutes interval = 30. -
Check Disk Usage (SSH) (SSH auth – key or password) — Executes the
df -Pcommand on the remote server. You must provide credentials (username + SSH key or password) stored in an n8n credential of type "SSH". -
Parse & Evaluate (No auth) — A Code node that parses the
stdoutfrom the SSH command. It reads thresholds from environment variables (DISK_WARN_PCTandDISK_CRIT_PCT, defaulting to 80% and 90%). For each mount point:- Compares usage percentage against thresholds.
- Uses
$getWorkflowStaticData('node')to remember the last known level (ok / warning / critical). - Only emits an alert when the level changes (including recovery messages when a disk returns below threshold).
- Outputs
{ hasAlerts, message, alerts }.
-
Any alerts? (No auth) — An IF node that checks
$json.hasAlerts(boolean true). If true, execution goes to the Telegram branch; otherwise the workflow ends silently. -
Send Telegram Alert (Telegram API – Bot Token auth) — Sends the alert message to a Telegram chat. The chat ID is read from
$env.TG_CHAT_ID. The node is set tocontinueErrorOutput(on error -> next output). On success, no further action. On error, execution flows into the email fallback. -
Send Email Fallback (SMTP auth – username/password or OAuth2) — Sends the same alert message via email. Uses
$env.SMTP_FROMand$env.SMTP_TOfor sender and recipient. This ensures alerts are never lost if Telegram is down.
Setup Instructions
-
Prerequisites:
- A Linux server with SSH access and passwordless sudo (if needed) or a user that can run
df -P. - A Telegram bot (create one via @BotFather) and obtain its API token.
- A Telegram chat ID (can be a group or your own ID).
- An SMTP server (e.g., Gmail, SendGrid, or your own) for email fallback.
- A Linux server with SSH access and passwordless sudo (if needed) or a user that can run
-
Environment Variables: Set the following in your n8n environment (e.g.,
.envor n8n UI > Workflow > Settings):DISK_WARN_PCT(default 80)DISK_CRIT_PCT(default 90)TG_CHAT_ID(e.g.,-123456789)SMTP_FROM(e.g.,[email protected])SMTP_TO(e.g.,[email protected])
-
Create Credentials in n8n:
- SSH: Add a credential of type "SSH" with the server host, port (22), username, and either password or private key.
- Telegram: Add a credential of type "Telegram API" with the bot token.
- SMTP: Add a credential of type "SMTP" with server, port, user, password (and choose authentication method).
-
Bind the credentials to the corresponding nodes in the workflow editor.
Use Cases & Variations
- Server Fleet Monitoring: Duplicate the SSH node or use a loop to check multiple servers; aggregate results in the Code node.
- Different Thresholds per Mount: Extend the Code node to read a JSON mapping from an env variable or static data.
- Escalation Chain: Instead of email fallback, add a PagerDuty or Slack node on error.
- Silence Recoveries: Modify the Code node to skip recovery messages (remove the
recoveredbranch). - Run less Frequently: Change the Schedule Trigger to hourly or daily.
- Add Grafana/Prometheus integration: Replace the SSH node with an HTTP request to your monitoring API.
This workflow is ideal for sysadmins and DevOps teams who need reliable, noise‑free disk monitoring without a full‑blown observability stack.
Workflow JSON
{
"name": "Disk space watchdog with tiered thresholds and Telegram alert",
"nodes": [
{
"parameters": {
"rule": {
"interval": [
{
"field": "minutes",
"minutesInterval": 30
}
]
}
},
"id": "f2b10000-0000-4000-8000-000000000001",
"name": "Schedule Trigger",
"type": "n8n-nodes-base.scheduleTrigger",
"typeVersion": 1.2,
"position": [
0,
0
]
},
{
"parameters": {
"resource": "command",
"command": "df -P"
},
"id": "f2b10000-0000-4000-8000-000000000002",
"name": "Check Disk Usage (SSH)",
"type": "n8n-nodes-base.ssh",
"typeVersion": 1,
"position": [
220,
0
]
},
{
"parameters": {
"jsCode": "// Parses the output of \"df -P\", compares it against tiered thresholds (WARN/CRIT)\n// and only reports when a mountpoint CHANGES level. The de-duplication uses n8n's\n// workflow static data, so a disk sitting at 85% for a week alerts once, not 336 times.\n// Thresholds are read from environment variables so the workflow needs no editing.\nconst warnPct = parseInt($env.DISK_WARN_PCT || '80', 10);\nconst critPct = parseInt($env.DISK_CRIT_PCT || '90', 10);\n\nconst raw = $input.first().json.stdout || '';\nconst lines = raw.trim().split('\\n').slice(1);\n\nconst staticData = $getWorkflowStaticData('node');\nif (!staticData.lastLevel) staticData.lastLevel = {};\n\nconst alerts = [];\nfor (const line of lines) {\n const parts = line.trim().split(/\\s+/);\n if (parts.length < 6) continue;\n const filesystem = parts[0];\n const capacityStr = parts[parts.length - 2];\n const mount = parts[parts.length - 1];\n const usedPct = parseInt(capacityStr.replace('%', ''), 10);\n if (Number.isNaN(usedPct)) continue;\n\n let level = 'ok';\n if (usedPct >= critPct) level = 'critical';\n else if (usedPct >= warnPct) level = 'warning';\n\n const prevLevel = staticData.lastLevel[mount] || 'ok';\n if (level !== prevLevel) {\n staticData.lastLevel[mount] = level;\n const availGB = (parseInt(parts[parts.length - 3], 10) / 1024 / 1024).toFixed(1);\n if (level !== 'ok') {\n alerts.push({ mount, filesystem, usedPct, level, availGB });\n } else {\n // Recovery is reported too, so a silent channel means \"nothing changed\",\n // not \"the workflow died\".\n alerts.push({ mount, filesystem, usedPct, level, availGB, recovered: true });\n }\n }\n}\n\nconst hasAlerts = alerts.length > 0;\nlet message = null;\nif (hasAlerts) {\n message = alerts.map(a => a.recovered\n ? `[OK] ${a.mount} back below threshold (${a.usedPct}%)`\n : `${a.level === 'critical' ? '[CRITICAL]' : '[WARNING]'} ${a.mount} (${a.filesystem}): ${a.usedPct}% used, ${a.availGB} GB free`\n ).join('\\n');\n}\n\nreturn [{ json: { hasAlerts, message, alerts } }];"
},
"id": "f2b10000-0000-4000-8000-000000000003",
"name": "Parse & Evaluate",
"type": "n8n-nodes-base.code",
"typeVersion": 2,
"position": [
440,
0
]
},
// ... truncated (copy to see full JSON)How to Import This Workflow
- 1Copy the workflow JSON above using the Copy Workflow JSON button.
- 2Open your n8n instance and go to Workflows.
- 3Click Import from JSON and paste the copied workflow.
Don't have an n8n instance? Start your free trial at n8nautomation.cloud
Related Templates
Automated n8n Workflow Backup to GitHub Repository
Overview This workflow automatically backs up every workflow in your n8n instance to a dedicated GitHub repository. It runs on a configurable schedule (or manually) and ensures that all your workflow JSON files are version-controlled and safely stored in a structured folder. The backup process intelligently handles both new workflows (creates a file) and existing ones (updates the file), making it ideal for disaster recovery, collaboration, or tracking changes over time. Step-by-Step Node Breakdown Schedule Trigger (No additional auth) — Triggers the workflow on a recurring interval. By default it runs hourly, but you can customize the schedule (e.g., daily at midnight) to suit your needs. Also supports manual execution via the Manual Trigger node. Manual Trigger (No auth) — Provides a manual button to run the backup immediately, useful for testing or on-demand backups. Get many workflows (Internal n8n API, no external credentials) — Fetches a list of all workflows from your n8n instance using the built-in n8n node. No separate API key is required; it uses the same authentication as your n8n session. Loop Over Items (No auth) — Iterates over each workflow in the list one at a time. This node processes workflows sequentially, preventing race conditions. Getafile (GitHub, OAuth2 / Personal Access Token) — Attempts to retrieve the existing workflow file from your GitHub repository at the path . If the file does not exist (i.e., a new workflow), the node’s error output is triggered. The expression in sanitizes the workflow name by replacing invalid characters (), converting to , and normalizing spaces. Convert to File1 (No auth) — Converts the retrieved GitHub file’s binary data back to a JSON object so it can be compared or overwritten. Extract from File1 (No auth) — Extracts the JSON content from the binary file, preparing it for an update operation. Edit a file (GitHub, OAuth2 / Personal Access Token) — If the workflow already exists on GitHub, this node updates the file with the latest JSON from your n8n instance. The commit message is dynamically generated (e.g., ). Convert to File (No auth) — Converts the current n8n workflow JSON into a binary file () with the workflow’s name as the filename. Create a file (GitHub, OAuth2 / Personal Access Token) — If the workflow is new (i.e., error output), this node creates a new file in the folder. The commit message includes the workflow name and . The workflow loops back to the Loop Over Items node to process the next workflow. The Sticky Note at the top serves as a comment. Setup Instructions GitHub account — You need a GitHub account and a repository (e.g., ) to store the backups. Create an empty repository or use an existing one. GitHub credential in n8n — Add a GitHub OAuth2 or Personal Access Token credential in n8n under Credentials > GitHub. Ensure the token has scope (or at least and ). Configure the nodes — - In Get many workflows, no changes needed. - In Getafile, Create a file, and Edit a file, update the and fields to match your GitHub username and repo name. - Optionally adjust the Schedule Trigger interval (set hours/minutes as desired). Error handling — The workflow references an external error workflow (). If you don’t have that, you should either create a simple error handler or remove the setting in the workflow settings. Use Cases & Adaptations Disaster recovery — Restore all workflows by downloading the JSON files from GitHub and importing them back into n8n. Version history — Track changes to workflows over time via GitHub commits and diffs. Multi-instance sync — Modify the workflow to run on multiple n8n instances, pushing to the same repo (be cautious with conflicts). Selective backup — Add a filter node after to only backup workflows with a specific tag or name pattern. Notification — Insert a Slack or email node after the loop to notify you when a backup completes or if an error occurs.
n8n Upgrade: Detect Affected Workflows with Broken Connections
Summary This workflow helps n8n administrators identify workflows that may have been affected by a past upgrade (specifically n8n version ) where multi-output nodes (like , , ) could have their output connections accidentally re-wired. It provides a self-service webhook endpoint that returns an HTML report listing all workflows with potentially broken connections, making it easy to audit and fix them. Node-by-Node Walkthrough Webhook (No auth) — Listens for HTTP GET requests at the path . When a user visits this URL in their browser, the workflow is triggered. The response mode is set to "Response Node", meaning the final output will be sent back directly. Get all workflows (API Key auth) — Uses the n8n API to fetch all workflows from the instance. You must configure this node with an n8n API credential (a personal access token created under Settings > n8n API). The node has no filters, so it retrieves every workflow. Parse potentially affected workflows (Code node, no auth) — A JavaScript code node that loops through each workflow, inspects its connections, and checks if any multi-output node (defined in the array) has empty outputs. If a node has fewer connected outputs than expected, it is flagged as potentially affected. The node outputs a JSON object with an array of affected workflows, each containing , , , and . Generate Report (HTML node, no auth) — Creates a static HTML document with a styled container, a heading, and an empty list. This serves as the shell for the interactive report generated by the next node. Serve HTML Report (Respond to Webhook node, no auth) — Takes the HTML template from the previous node and injects JavaScript that parses the affected workflows data (from the code node) and dynamically builds a list of clickable links. Each link opens the workflow in a new tab so the admin can inspect and fix the connections. The response headers are set to . Setup Instructions Prerequisites: You must have admin access to the n8n instance (the workflow must be run by the instance owner). Create an n8n API key: Go to Settings > n8n API in your n8n instance and generate a personal access token. Copy the token. Configure the "Get all workflows" node: Add an n8n credential of type "API Key" and paste the token. Leave the filters empty. Customize multi-output nodes (if needed): The code node contains a list with the default nodes (, , ). If you have community nodes with multiple outputs, add them to this array with their correct output count. Activate the workflow: Toggle the workflow to active. Use the report: Open your browser and navigate to . The page will list all affected workflows. Click on a row to open the workflow in a new tab — inspect the connections and re-wire them if needed. Use Cases & Variations Post-upgrade audit: Run this workflow after every n8n upgrade to catch connection issues early. Customized detection: Extend the array in the code node to include any custom node type that has multiple outputs. Slack/Email notification: Instead of serving an HTML report, you could send the list of affected workflows to a Slack channel or email using additional nodes. Scheduled scanning: Replace the Webhook trigger with a Schedule trigger to run the check daily and automatically notify the admin.
Manual Trigger with Error Handler - Production Template
Overview This is a foundational n8n workflow template designed to demonstrate a robust, production-ready pattern for manual workflow execution with integrated error handling. It provides a clean starting point for building more complex automations by establishing best practices for error management and workflow structure from the outset. The workflow is intentionally minimal but includes critical production features: a manual trigger for on-demand execution, a dedicated error handler node that gracefully stops execution on failure, and comprehensive workflow settings configured for reliability (retry logic, timeout limits, and execution tracking). This makes it ideal for users who want to learn n8n's error handling capabilities or need a reliable skeleton for mission-critical automations. Workflow Steps Manual Trigger (No auth) — This is the starting point of the workflow. It allows you to run the workflow manually by clicking the "Execute Workflow" button in the n8n editor. No authentication is required for this trigger node itself. The node has no additional parameters configured, meaning it simply fires when manually activated. Error Handler (No auth) — Connected as an error workflow handler (though in this JSON it is not wired via connections, it is placed as a standalone error-catching node). This node uses the "Stop and Error" type, which means if any error occurs during workflow execution, this node will catch it and stop the workflow with a custom error message: "Workflow execution error". The parameter is empty, so no additional error handling behavior (like sending notifications) is configured. No authentication is required. Setup Instructions No external accounts required — This workflow uses only built-in n8n nodes (Manual Trigger and Stop & Error). You do not need any third-party service accounts or API keys. Import the workflow — Copy the JSON and paste it into your n8n instance via "Workflows > Add Workflow > Import from JSON". Customize the error message — If desired, edit the Error Handler node's "Message" parameter to provide a more specific error description relevant to your use case. Add your logic — Connect additional nodes after the Manual Trigger to perform your actual automation tasks. The Error Handler will automatically catch any errors from those nodes. Configure workflow settings — Review the existing settings (retry on fail, timeout, etc.) and adjust them to match your production requirements. Use Cases and Variations Learning template — Use this as a teaching tool to understand how error handling works in n8n workflows. Production skeleton — Start every new automation by duplicating this workflow, then add your business logic nodes between the trigger and error handler. Error notification system — Extend the Error Handler by adding a Slack, email, or webhook node after it to send alerts when errors occur. Multi-trigger adaptation — Replace the Manual Trigger with a Schedule Trigger, Webhook Trigger, or Event Trigger to make the workflow run automatically. Conditional error handling — Add an IF node before the Error Handler to route different error types to different handling logic (e.g., retry vs. notify vs. log).