LoginSignup
13
11

More than 5 years have passed since last update.

systemd のサービスで OnFailure でメール通知

Posted at

下記のほぼそのまんまですけど、systemd のサービスで OnFailure でメール通知してみました。

環境は下記の通り。

  • centos-release-7-2.1511.el7.centos.2.10.x86_64
  • systemd-219-19.el7_2.11.x86_64

メールを送るためのサービスを作ります。

/etc/systemd/system/failure-email@.service

[Unit]
Description = failure email for %I

[Service]
Type = oneshot
ExecStart = /bin/sh -c 'systemctl status --full "$1"|mail -S sendwait -s "[$HOSTNAME]systemd failure $1" root' -- %i
User = nobody
Group = systemd-journal

適当にそれっぽいサービスのスクリプトを作ります。

/usr/local/bin/oreservice

#!/bin/bash
while sleep 1; do
    echo "hello oreservice"
done

実行属性を付けます。

chmod +x /usr/local/bin/oreservice

ユニットファイルを作ります。OnFailure に failure-email@%n.service を指定します。

/etc/systemd/system/oreservice.service

[Unit]
Description = oreservice
OnFailure = failure-email@%n.service

[Service]
Type = simple
Restart = always
ExecStart = /usr/local/bin/oreservice

[Install]
WantedBy = multi-user.target

systemd をリロードしてユニットファイルを読み込みます。

systemctl daemon-reload

サービスを開始します。

systemctl start oreservice.service
systemctl status oreservice.service

おもむろに殺します。

systemctl kill oreservice.service -s SIGKILL

メールで通知されたら成功です。


OnFailure = failure-email@%n.service

これは、ユニットが failure になったら failure-email@oreservice.service.service ユニットを開始する、という意味です。

failure-email@.service はアットマークを含むのでテンプレートユニットです。これを failure-email@oreservice.service.service のように呼び出した場合、ユニットの %i には oreservice.service が渡ります。

なので、下記のように直接実行してメールの通知を確認することもできます。

systemctl start failure-email@oreservice.service.service
13
11
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
13
11