AWS EC2 Prior To Shutdown Script

Dale Frohman
2 min readApr 25, 2021

Ever need to run a script prior to a planned or unplanned reboot or shutdown?

We had a need recently to run a script prior to an EC2 instance being shutdown. This would ensure that a proper fail-over happened and that the environment was updated with the new topology.

In short here is what we did to solve the challenge:

  1. Create your script

#!/bin/bash
your awesome code here

  1. Create a system.d service file in /usr/lib/systemd/system/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/script/my_awesome_script.sh
RemainAfterExit=yes
Type=oneshot

[Install]
WantedBy=multi-user.target

  1. Add this service to multi-user.target

Systemctl enable shutdown.service

  1. Start the service

Systemctl start shutdown.service

  1. Test

Reboot your EC2 instance

Some additional notes:

If you are writing to the filesystem you may need to add this to your script

RequiresMountsFor=/path/to/my/filesystem

You may need to add a “sleep 60” to your init.d shutdown script for a dependency service. We had to add this to a database script to ensure another script had time to run before terminating the process.

After much trial and tribulation, we were able to execute our shutdown script. We tested writing to the filesystem and ensured that our script was executed prior to the network shutting down.

I hope this helps someone else out there :)

--

--

Dale Frohman

Principal Site Reliability Engineer. Cyber Security Professional. Technologist. Leader.