I’ve written a little module to send systemd unit failures to Telegram.
However for the moment I have used the built paths to the scripts /run/current-system/sw/bin/SCRIPT_NAME
but I reckon it would be better if I could reference them with something like ${send-to-telegram}/bin/send-to-telegram
.
How would you do this with the writeShellScriptBin
function?
I reckon it’s easier to use that function than to write a proper package for those small scripts?
1 Like
tejing
August 27, 2022, 4:27pm
2
In fact, that should be exactly correct.
You can also just use writeShellScript
instead, take them out of environment.systemPackages
, and use ${send-to-telegram}
with no path after it.
2 Likes
Ah right! Since I don’t really use it manually I can limit it, to just the systemd services.
Thanks a ton!
The final result looks now like this:
{ custom, pkgs, ... }:
let
telegram-notify-env = "/home/${custom.username}/.nixos/secrets/passwords/telegram_notify_env";
send-to-telegram = pkgs.writeShellScript "send-to-telegram" ''
export $(${pkgs.gnugrep}/bin/grep -v '^#' ${telegram-notify-env} | ${pkgs.findutils}/bin/xargs)
URL="https://api.telegram.org/bot$TELEGRAM_KEY/sendMessage"
${pkgs.curl}/bin/curl -s -d "chat_id=$CHAT_ID&disable_web_page_preview=1&text=$1" $URL > /dev/null'';
unit-status-telegram = pkgs.writeShellScript "unit-status-telegram" ''
UNIT="$1"
UNITSTATUS="$(systemctl status $UNIT)"
ALERT="$(echo -e "\u26A0")"
${send-to-telegram} "$ALERT Unit failed $UNIT $ALERT
Status:
$UNITSTATUS"'';
in
{
systemd.services."unit-status-telegram@" = {
description = "Unit Status Telegram Service";
unitConfig = {
After = "network.target";
};
serviceConfig = {
Type = "simple";
ExecStart = "${unit-status-telegram} %I";
};
};
}
And can be used on a systemd service definition like this:
onFailure = [ "unit-status-telegram@%n.service" ];