Labels

Wednesday, 24 May 2017

How to run a script at reboot with systemd service?

Run a Script at Reboot Using Systemd service

NOTE: Works on latest linux distos like ubuntu 16.04, which uses systemd as a init service. You can check it by using below command
ls -l /sbin/init

output looks like below
lrwxrwxrwx 1 root root 20 Jan 19 03:34 /sbin/init -> /lib/systemd/systemd
Run the service unit as a normal service - have a look at the [Install] section. So everything has to be thought reverse, dependencies too. Because the shutdown order is the reverse startup order. That's why the script has to be placed in ExecStop=.
The following solution is working for me:
[Unit]
Description=...

[Service]
Type=oneshot
RemainAfterExit=true
ExecStop=<your script/program>

[Install]
WantedBy=multi-user.target
RemainAfterExit=true is needed when you don't have an ExecStart action. 
After creating the file, make sure to systemctl daemon-reload and systemctl enable yourservice.
Note: At ubuntu 16.04 you must have a ExecStart=/bin/true --> which means under [service] add the ExecStart=/bin/true, before ExecStop.

Case study:

You can verify the service working or not based on the message given in the Description under [Unit] section.
If Description=My Magic Script, then after issuing reboot we can see message from the log like "Stopping My Magic Script..." and another print like "Stopped My Magic Script". At startup log shows like "Starting My Magic Script..." and which will execute /bin/true binary and exits.
Important thing to observe is binary gets exited whereas service wont die..why because there is property in service which makes it not to die and the property is "RemainAfterExit=true".
We can see the service status whether it actually died or not by running the below command
systemctl status <service_name>

To get full understanding of each stanza please follow the below systemd manual.
References:
https://www.freedesktop.org/software/systemd/man/systemd.service.html#
 

No comments:

Post a Comment