大网数据广告活动
服务器运维问答

Run a backup script at systemd shutdown (e.g. copy logs to S3 before instance termination by auto scaling)

· 52CE 我爱测

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 …

问题原文

原帖链接 · Shivanshi Srivastava · CC BY-SA 4.0

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 · CC BY-SA 4.0

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.

摘自公开归档,保留原文语言,版式经整理,外部媒体与邮箱地址已移除。

资料来源与适用范围

资料来源
Server Fault
适用范围
以原帖系统、软件版本与发布日期为准(2018-12-17)
内容语言
中文;命令、路径和错误标识保留技术原文
本地收录日期
2026-11-15
授权说明
CC BY-SA 4.0

正文与所需资源由本站本地存储。查看来源及更新记录 ↗

请按适用版本和实际日志确认原因;本站没有对每一种系统或设备逐项执行文中的操作。