AWS EC2 Prior To Shutdown Script
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:
- Create your script
#!/bin/bash
your awesome code here
- 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
- Add this service to multi-user.target
Systemctl enable shutdown.service
- Start the service
Systemctl start shutdown.service
- 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 :)