Run a script during shutdown/termination of an aws instance

2

I need to execute a script during shutdown/termination of an AWS instance(debian). I added my script to the /etc/init.d/myscript and a symlink to /etc/rc0.d/K01myscript however I noticed that when I terminate the instance I don't see that my script is executed. Any idea?

Vishnu Nair

Posted 2015-12-17T10:51:25.560

Reputation: 133

1How do you know it's not being executed? Are there any local ~ references, or programs that are expected to be in the path? May have to explicitly state the location of whatever needs to run. – Xen2050 – 2015-12-17T11:10:10.097

I'll explain my use case. I'm using Sensu for monitoring and my app is running under an ASG. So I use systemd for the sensu client service. When an instance is boot up, it will automatically connected to the Sensu master server. What I need is when the instance goes down, it needs to deregister from the Sensu master server. I had tried the script manually and it's working fine as expected. What I want is to execute this script during the shutdown process. – Vishnu Nair – 2015-12-17T11:24:05.163

Answers

2

So I use systemd for the sensu client service

If this is indeed so, then you do not use init scripts at all. All you need to do is to add the two following lines to your systemd service:

 RemainAfterExit=yes
 ExecStop=/path/to/executable/script

The first option instructs systemd to treat the service as a daemon, i.e. to treat it as running even though all processes have died already; the second instruction points systemd to the cleanup script, which you will have to provide.

MariusMatutiae

Posted 2015-12-17T10:51:25.560

Reputation: 41 321