Migrate basic upstart script to systemd

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:

  • Phillipp Klaus doing this in 2013
  • Thomaz Fritz doing this in 2014
  • unknown people doing this in 2013

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/[email protected], 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.