I have a critical application which is run as a service by systemd.
It is set up to restart as soon as there is a failure.
How to send an email if the application restarts?
Server Fault is a question and answer site for system and network administrators. It only takes a minute to sign up.Sign up to join this community
First you need two files: an executable for sending the mail and a .service for starting the executable. For this example, the executable is just a shell script using
/usr/local/bin/systemd-email: #!/bin/bash /usr/bin/sendmail -t <<ERRMAIL To: $1 From: systemd <root@$HOSTNAME> Subject: $2 Content-Transfer-Encoding: 8bit Content-Type: text/plain; charset=UTF-8 $(systemctl status --full "$2") ERRMAIL
Whatever executable you use, it should probably take at least two arguments as this shell script does: the address to send to and the unit file to get the status of. The
.service we create will pass these arguments:
/etc/systemd/system/status-email-user@.service: [Unit] Description=status email for %i to user [Service] Type=oneshot ExecStart=/usr/local/bin/systemd-email address %i User=nobody Group=systemd-journal
Where user is the user being emailed and address is that user's email address. Although the recipient is hard-coded, the unit file to report on is passed as an instance parameter, so this one service can send email for many other units. At this point you can start
firstname.lastname@example.org to verify that you can receive the emails.
Then simply edit the service you want emails for and add
OnFailure=status-email-user@%n.service to the
%n passes the unit's name to the template.
You may try to use systemd service option ExecStartPost.
The description is available here:
There can be more declarations of this option in the service definition file. It's triggered one by one.
You'll have some examples in your system as well.
You can create a shell script to check service status and send email while server booting up. This link might help you