2

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.

  • 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 1 at 13:11
1

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.