# Mail the tail of a failed unit's journal: OnFailure=alert-mail@%n.service # Sends through the SMTP account Forgejo uses (sops: alert/*). { config, pkgs, ... }: let send = pkgs.writers.writePython3 "alert-mail" { flakeIgnore = [ "E501" ]; } '' import os import smtplib import socket import subprocess import sys from email.message import EmailMessage unit = sys.argv[1] log = subprocess.run( ["journalctl", "-u", unit, "-n", "60", "--no-pager", "-o", "cat"], capture_output=True, text=True, ).stdout msg = EmailMessage() msg["Subject"] = f"[{socket.gethostname()}] {unit} failed" msg["From"] = os.environ["ALERT_SMTP_USER"] msg["To"] = os.environ["ALERT_RECIPIENT"] msg.set_content(log) with smtplib.SMTP(os.environ["ALERT_SMTP_HOST"], int(os.environ["ALERT_SMTP_PORT"]), timeout=30) as s: s.starttls() s.login(os.environ["ALERT_SMTP_USER"], os.environ["ALERT_SMTP_PASSWORD"]) s.send_message(msg) ''; in { sops.secrets."alert/smtp_user" = { }; sops.secrets."alert/smtp_password" = { }; sops.secrets."alert/recipient" = { }; sops.templates."alert.env".content = '' ALERT_SMTP_HOST=smtp.fastmail.com ALERT_SMTP_PORT=587 ALERT_SMTP_USER=${config.sops.placeholder."alert/smtp_user"} ALERT_SMTP_PASSWORD=${config.sops.placeholder."alert/smtp_password"} ALERT_RECIPIENT=${config.sops.placeholder."alert/recipient"} ''; systemd.services."alert-mail@" = { description = "Mail the failure of %i"; path = [ config.systemd.package ]; serviceConfig = { Type = "oneshot"; EnvironmentFile = config.sops.templates."alert.env".path; ExecStart = "${send} %i"; }; }; }