Ubuntu – Migrate basic upstart script to systemd

systemdupstart

I just upgraded a server from Ubuntu 14.10 to 15.04, and a couple of services that I start via custom upstart scripts are no longer running.

My understanding is that I need to re-write them as systemd services, but the thought of learning the entire systemd system overnight is a little daunting.

The upstart script simply launches autossh at startup, and I have a couple of other similar scripts that launch long-running processes.

#/etc/init/autossh.conf

description "Maintain a permanent SSH tunnel to <other_server>"

start on started mountall
stop on shutdown

exec autossh -N other_server

How can I re-write this as a systemd service?

Best Answer

the first rule for migrating to systemd

At this point, in 2015, it's most likely that someone has already done it.

systemd has been around for some years. And there has been a whole cottage industry of people writing unit files and publishing them. GitHub, in particular, seems to attract repositories of collections of service units.

Indeed simply searching the WWW for autossh.service (as a phrase) turns up:

a template unit

That said, as I've pointed out in several places on StackExchange alone, this sort of migration is not a mechanistic process, and sometimes just robotically translating from whatever one has to a unit file is doing things wrongly, or at least poorly. In this case, autossh is positively panting to be handled with a template unit, that it is instantiated into actual service units, parameterized by the target name. So as /etc/systemd/system/autossh@.service, have:

[Unit]
Description=AutoSSH service for a reverse tunnel from %i 
After=network.target

[Service]
User=autossh
EnvironmentFile=/etc/%p/%i.conf
ExecStart=/usr/bin/autossh -M 0 -q -N $SSH_USER@%i $SSH_OPTIONS

[Install]
WantedBy=multi-user.target

Create a file named /etc/autossh/other_server.example.conf with, minimally:

SSH_USER=joe

All of the usual controls then apply:

  • systemctl enable autossh@other_server.example — Enable an instance to be automatically started at bootstrap.
  • systemctl start autossh@other_server.example — Manually start that instance immediately.
  • systemctl status autossh@other_server.example — See its status.

And yes, the first rule even applies to this. Searching, one can find that I was beaten to this, by just under a fortnight, by Greg Freemyer at OpenSUSE.

Related Question