So the answer is not really AWS specific, but it is working for me now (tested on EC2 instance stopping and terminating).
- I've created a system.d service file:
/usr/lib/systemd/system/my_shutdown.service
[Unit]
Description=my_shutdown Service
Before=shutdown.target reboot.target halt.target
Requires=network-online.target network.target
[Service]
KillMode=none
ExecStart=/bin/true
ExecStop=/path/to/my_script.sh
RemainAfterExit=yes
Type=oneshot
[Install]
WantedBy=multi-user.target
- Added this service to multi-user.target:
systemctl enable my_shutdown.service
Alternatively you can manually create the symlink:
ln -s /usr/lib/systemd/system/my_shutdown.service /etc/systemd/system/multi-user.target.wants/my_shutdown.service
- Started the service and tested by stopping/terminating the instance.
systemctl start my_shutdown.service
My understanding:
- Description: a description of our service.
- Before: we want our service to stop before these targets are started.
- Requires: our service requires that network capabilities are available. These targets must not be stopped before our service starts/stops.
- KillMode: none; do not kill our process.
- ExecStart: /bin/true; a command that does nothing but returns a success. Run when are service is started.
- ExecStop: the script to run. Run when are service is being stopped.
- RemainAfterExit: consider our service active even when all its processes exited.
- Type: oneshot; it is expected that the process has to exit before systemd starts follow-up units.
- WantedBy: the target we want to add our service to.
References:
- https://www.freedesktop.org/software/systemd/man/systemd.service.html
- https://www.freedesktop.org/software/systemd/man/systemd.kill.html#
- https://www.freedesktop.org/software/systemd/man/systemd.special.html
- https://www.freedesktop.org/software/systemd/man/systemd.target.html