Initscript hack that allows an application to control itself

July 15, 2013, revised February 2, 2014 Debian initscripts server configuration Ubuntu

I was faced with a curious challenge while making initscripts for a webapp (for Unicorn, delayed job, and the like).

I wanted to have a normal root-owned initscript, so that it can be autostarted on boot. But, I still wanted the app user to be able to control its own scripts without sudo. For example, this would allow reloading Unicorn and other services after a Capistrano deploy.

The solution was to allow anyone to start the script, but, unless the current user is the app user, sudo to that user before actually executing any commands. It goes something like this:

USER=myappuser
DAEMON_COMMAND="sillyexample start --daemonize"

if [ "$USER" != `/usr/bin/whoami` ]; then
  DAEMON_COMMAND="sudo -u $USER -- $DAEMON_COMMAND"
fi

eval "$DAEMON_COMMAND"

The script must be owned by root and have 0755 permissions.

It can be used by anyone with sudo permissions, plus the app user himself.

Buy Me a Coffee at ko-fi.com