4

I am trying to send log files to S3 before instance termination. I created .service file in /lib/systemd/system-shutdown/upload-backup.service, which is this.

Description=Testing
Before=shutdown.target reboot.target halt.target
Requires=network-online.target network.target
DefaultDependencies=no
[Service]
ExecStart=/bin/true
ExecStop=/home/ubuntu/upload_log_to_s3.sh
RemainAfterExit=yes
Type=oneshot
[Install]
WantedBy=multi-user.target

Note: upload_log_to_s3 being the script present in home and copies the file. This is working independently, so has no issues.

I have also created a soft link for this file in /etc/systemd/system/shutdown.target.wants/ and also enabled systemctl.

But the script is not running while shutdown or reboot. Please explain the mistake and where I am wrong.

Amir
  • 837
  • 8
  • 17
  • 1
    Just to note, that the directory `/lib/systemd/system-shutdown/` (see `man systemd-shutdown`) should contain **executables** (not service unit definitions) that will be run _very_ late in the shutdown process – too late for anything that requires network connectivity like uploading to S3. – Amir Jan 01 '19 at 13:11

1 Answers1

4

The trick that worked for me was to use a service unit’s ExecStop= to run the script, but the service unit is otherwise “normal”, i.e. WantedBy=multi-user.target.

In order to make sure that networking is still available when the command is executed, I added After=network.target.

Since I care about the log files generated by a particular service of interest, I added Before=interesting.service – in order to make sure that the command is run only after the interesting service had been stopped.

Note that when stopping units, systemd applies the order dependencies of Before= and After= in reverse, so the above is as intended.

For good measure, I also set the User= and Group= so that the script does not run as root.

[Unit]
Before=interesting.service
After=network.target
[Service]
Type=oneshot
RemainAfterExit=yes
ExecStop=/home/ubuntu/upload_log_to_s3.sh
User=ubuntu
Group=ubuntu
[Install]
WantedBy=multi-user.target

Place the file at /etc/systemd/system/upload-backup.service; enable and start it with sudo systemctl enable upload-backup.service --now.

Once enabled, the service will be started automatically at boot. Once started, it will sit there doing nothing until shutdown, and on shutdown it will run the script.

Amir
  • 837
  • 8
  • 17