Skip to content
ShellOps Daily

Linux server hardening, systemd, and Bash automation tips

Disk & Logs

Monitor Disk Space and Send Webhook Alert

Victor Novak8 min read

Monitoring disk space is a critical task for system administrators and DevOps engineers, as full disks can lead to service outages, data loss, and performance degradation. Automating this process with a monitor disk space and send webhook alert solution ensures timely interventions and minimizes downtime. This article guides you through setting up a reliable system to track disk usage and send real-time alerts via a webhook. By combining command-line tools with webhooks, you can create a proactive monitoring strategy that fits into your existing infrastructure. The steps outlined here are practical and adaptable, making it easy to integrate into your workflows. Whether you're managing a single server or a distributed environment, the tools and techniques described will help you maintain optimal resource usage. The final example provides a complete script that you can customize for your specific needs.

Why Monitoring Disk Space Matters

Disk space is a critical resource for server stability and performance. When storage reaches capacity, it can lead to severe operational issues, including service failures, data loss, and system unresponsiveness. Proactive monitoring is essential to prevent these scenarios and maintain smooth operations. Integrating real-time alerts through webhooks provides a flexible and efficient way to address disk space issues before they escalate.

The Risks of Full Disk Space

Running out of disk space can cause a cascade of problems. Applications may fail to write data, databases might become inaccessible, and system logs could stop recording critical information. Additionally, some operating systems and services may halt entirely when storage is full, leading to unexpected downtime. These issues not only disrupt service availability but also complicate troubleshooting and recovery efforts. Therefore, maintaining sufficient disk space is a foundational aspect of server management.

How Webhooks Enable Real-Time Notifications

Webhooks enable real-time notifications by sending data to a specified endpoint whenever an event occurs. This allows system administrators to receive alerts instantly, regardless of their location. By integrating webhooks with disk monitoring tools, teams can automate responses, such as triggering alerts in monitoring dashboards or sending notifications to on-call personnel. This integration ensures that issues are addressed promptly, minimizing the risk of prolonged outages and improving overall system reliability.

Using Df -h to Monitor Disk Usage

The `df -h` command is a fundamental tool for monitoring disk usage on Linux systems. It provides a human-readable summary of available and used disk space, making it easier to interpret compared to raw numerical values. By using `df -h`, system administrators can quickly assess storage utilization and identify potential issues before they escalate.

Understanding Df -h Output

The `df -h` command displays disk space in a user-friendly format, using units like KB, MB, and GB. Each line in the output represents a mounted filesystem, showing total space, used space, available space, and usage percentage. This information is crucial for identifying which partitions are nearing capacity and which are underutilized. The output also includes the mount point, helping to pinpoint the exact location of the storage issue.

Setting Thresholds for Disk Alerts

Setting thresholds for disk alerts is essential to automate monitoring and ensure timely responses to critical issues. A common starting point is 85% usage, as this balance between performance and alert sensitivity helps avoid unnecessary notifications while ensuring sufficient space remains for system operations. Thresholds should be adjusted based on the specific needs of the server, such as the type of workload and the criticality of the data stored. By combining `df -h` with conditional logic in scripts, administrators can create targeted monitoring that triggers alerts when predefined limits are exceeded.

Setting Up a Bash Script for Disk Monitoring

A Bash script is an essential tool for automating disk space monitoring, allowing system administrators to detect when storage thresholds are reached and trigger alerts via webhooks. This script leverages `df -h` to gather disk usage data, uses conditional checks to determine if a threshold is exceeded, and employs `curl` to send alerts to a specified webhook endpoint. By incorporating error handling and logging, the script becomes more reliable and easier to debug.

  1. The script should start by defining variables for thresholds, such as 90% disk usage, and the webhook URL. These variables make the script more flexible and easier to adjust without modifying the logic.
  2. Next, the script uses `df -h` to fetch disk usage data, then parses the output to extract the percentage used. A conditional check compares the usage against the defined threshold.
  3. If the threshold is exceeded, the script sends a webhook request using `curl` to notify the designated endpoint. Properly formatting the request with JSON data ensures compatibility with most webhook services.
  4. To improve reliability, the script should include error handling for failed `curl` requests and logging to record when alerts are triggered. This helps in troubleshooting and auditing script behavior.

Script Structure and Logic

The script structure begins with defining variables for the threshold and webhook URL. These are typically set at the top of the script to allow easy modification. Following this, the script runs `df -h` to collect disk usage information, which is then parsed to extract the percentage of space used. This parsed value is compared against the threshold to determine if an alert is needed.

Testing the Disk Monitoring Script

Testing the script involves simulating disk usage to ensure it behaves as expected. One method is to fill a disk partition to the defined threshold using a tool like `dd` or by writing files manually. After triggering the script, verify that it sends a webhook request and logs the event correctly. If the script fails, reviewing the logs and checking for syntax errors can help identify and resolve the issue.

Sending Webhook Alerts with Curl

Sending webhook alerts with `curl` is a powerful way to notify external services when disk space thresholds are breached. By leveraging HTTP POST requests, you can integrate your monitoring script with tools like Prometheus, Grafana, or Slack, ensuring real-time visibility into system health.

Understanding Webhook Syntax

Webhook syntax involves specifying a URL endpoint and defining the data format, typically JSON. When sending alerts, it's essential to include headers such as `Content-Type: application/json` to ensure the payload is correctly interpreted by the receiving service. The JSON payload should contain relevant details like the disk usage percentage, threshold, and system metrics to provide context for the alert.

Configuring Curl for Webhook Requests

To configure `curl` for webhook requests, use environment variables to store sensitive information like API keys or authentication tokens. This approach enhances security by keeping credentials out of the script itself. Additionally, ensure the script has proper permissions to execute `curl` and access system resources, such as reading disk usage data from `/proc/diskstats` or `/etc/mtab`. Testing the script with verbose output can help identify issues with headers, payloads, or network connectivity.

Putting It All Together: A Complete Example

This section provides a complete example of a script that monitors disk usage, checks thresholds, and sends a webhook alert. It integrates the `df -h` command, threshold logic, and `curl` to send real-time notifications.

  1. Create a script file, such as /opt/disk_alert.sh, and paste the complete script into it.
  2. Define thresholds and webhook URLs at the top of the script for easy customization.
  3. Use `if` statements to check if disk usage exceeds the defined limit.
  4. Implement error handling to log failures and prevent script interruptions.
  5. Save the script in a secure location and set appropriate file permissions.

Sample Script for Disk Monitoring

The script begins by defining variables for thresholds and webhook URLs. These settings allow users to adjust alert limits and notification endpoints without modifying the core logic. It then runs the `df -h` command to gather disk usage data, which is parsed to extract mount points and usage percentages. The script uses `if` statements to compare these values against the defined thresholds, triggering the alert process when a threshold is exceeded.

Troubleshooting Script Execution

When an alert is triggered, the script uses `curl` to send a POST request to the specified webhook URL. It includes details such as the mount point, usage percentage, and current time in the payload to ensure the alert is informative. Error handling is built into the script to catch and log any issues during execution, such as failed curl requests or unexpected output formats. This prevents the script from crashing and ensures continuous monitoring even during unexpected conditions.

Frequently Asked Questions

How do I set a disk usage threshold in a bash script?

Set a disk usage threshold in a bash script by comparing the output of `df -h` against a defined percentage. For example, use `if [ $(df -h / | grep -v 'Use%' | awk '{print $5}' | cut -d'%' -f1) -gt 90 ]; then` to trigger an alert when usage exceeds 90%.

Can I use curl to send alerts to multiple webhooks?

Yes, you can use `curl` to send alerts to multiple webhooks by including multiple URLs in the script. Each webhook URL should be specified as a separate `curl` command, ensuring each request is sent to the appropriate endpoint.

What should I do if my script fails to send a webhook alert?

If your script fails to send a webhook alert, check for errors in the `curl` command, verify the webhook URL, and ensure the script has the necessary permissions. Use `curl -v` to get detailed output and troubleshoot the issue.

How do I test my disk monitoring script without affecting the system?

Test your disk monitoring script using a virtual machine, a test directory, or by simulating high disk usage with tools like `dd` or `fallocate`. This ensures the script works without impacting real data or system performance.

Next Steps and Final Thoughts

Monitoring disk space is critical to avoiding system downtime and data loss. By combining `df -h`, bash scripts, and webhook alerts, you can automate alerts and maintain system stability. This approach offers flexibility and real-time notifications for critical disk usage events.

To get started, create a script that checks disk usage and sends alerts via a webhook. Testing and configuring thresholds are essential for reliability. You can further enhance this by integrating with monitoring tools or expanding the script to monitor multiple drives.