add notify service

This commit is contained in:
Mark Eaton
2026-01-11 00:00:20 -05:00
parent eec27c3b00
commit 9a070c81be
4 changed files with 87 additions and 0 deletions
+8
View File
@@ -0,0 +1,8 @@
[Unit]
Description=Send Teams failure notification for %i
[Service]
Type=oneshot
ExecStart=/usr/local/bin/notify-teams.sh %i failure
# Load webhook URL from environment file
EnvironmentFile=-/etc/notify-teams.conf
+8
View File
@@ -0,0 +1,8 @@
[Unit]
Description=Send Teams success notification for %i
[Service]
Type=oneshot
ExecStart=/usr/local/bin/notify-teams.sh %i success
# Load webhook URL from environment file
EnvironmentFile=-/etc/notify-teams.conf
+3
View File
@@ -0,0 +1,3 @@
# /etc/notify-teams.conf
# Teams incoming webhook URL
TEAMS_WEBHOOK_URL="https://outlook.office.com/webhook/your-webhook-url-here"
+68
View File
@@ -0,0 +1,68 @@
#!/bin/bash
# notify-teams.sh - Send Teams notifications for systemd service events
#
# Usage: notify-teams.sh <service-name> <status>
# status: "success" or "failure"
#
# Configuration:
# Set TEAMS_WEBHOOK_URL environment variable or create /etc/notify-teams.conf
set -euo pipefail
SERVICE_NAME="${1:-unknown}"
STATUS="${2:-unknown}"
HOSTNAME=$(hostname)
TIMESTAMP=$(date '+%Y-%m-%d %H:%M:%S %Z')
# Load webhook URL from config file if not set
if [[ -z "${TEAMS_WEBHOOK_URL:-}" ]] && [[ -f /etc/notify-teams.conf ]]; then
source /etc/notify-teams.conf
fi
if [[ -z "${TEAMS_WEBHOOK_URL:-}" ]]; then
echo "Error: TEAMS_WEBHOOK_URL not set" >&2
exit 1
fi
# Set color and title based on status
if [[ "$STATUS" == "success" ]]; then
THEME_COLOR="00FF00"
TITLE="Service Completed Successfully"
EMOJI="✓"
else
THEME_COLOR="FF0000"
TITLE="Service Failed"
EMOJI="✗"
fi
# Get recent logs for context (last 15 lines)
RECENT_LOGS=$(journalctl -u "$SERVICE_NAME" -n 15 --no-pager 2>/dev/null | tail -15 || echo "No logs available")
# Escape special characters for JSON
escape_json() {
printf '%s' "$1" | python3 -c 'import json,sys; print(json.dumps(sys.stdin.read()))'
}
ESCAPED_LOGS=$(escape_json "$RECENT_LOGS")
# Build and send the payload
curl -s -H "Content-Type: application/json" -d "{
\"@type\": \"MessageCard\",
\"@context\": \"https://schema.org/extensions\",
\"themeColor\": \"${THEME_COLOR}\",
\"title\": \"${EMOJI} ${TITLE}\",
\"summary\": \"${SERVICE_NAME} ${STATUS} on ${HOSTNAME}\",
\"sections\": [{
\"facts\": [
{\"name\": \"Service\", \"value\": \"${SERVICE_NAME}\"},
{\"name\": \"Status\", \"value\": \"${STATUS}\"},
{\"name\": \"Host\", \"value\": \"${HOSTNAME}\"},
{\"name\": \"Time\", \"value\": \"${TIMESTAMP}\"}
]
}, {
\"title\": \"Recent Logs\",
\"text\": ${ESCAPED_LOGS}
}]
}" "$TEAMS_WEBHOOK_URL"
echo "Notification sent for ${SERVICE_NAME} (${STATUS})"