SSH tunnel with Systemd service

This is a service unit I use to setup my ssh tunnels. Save it under ''$HOME/.config/systemd/user/autossh@.service'' for example.


[Unit]
Description=SSH Tunnel %i

# This whole mess is so the service won't start until WiFi is online.

Wants=network-online.target NetworkManager-wait-online.service                                                                                                                                                                         
After=network.target network-online.target NetworkManager-wait-online.service                                                                                                                                                          

[Service]
Type=exec
ExecStart=/usr/bin/ssh -vCN -o "ExitOnForwardFailure yes" %i
KillMode=process
Restart=always
RestartSec=5

[Install]
WantedBy=multi-user.target

That way I can restart a specific tunnel like ''systemctl --user restart autossh@tunnel1''.

And since it runs as my user the tunnel1 ssh config is in ''$HOME/.ssh'' as is custom.

I don't know of a way to write dependencies between the tunnels but it doesn't matter much because the tunnels I have that depend on other tunnels will restart every 5 seconds until they're live.

To figure out your dependencies in After and Wants you can run this command.

$ systemctl is-enabled NetworkManager-wait-online.service systemd-networkd-wait-online.service
enabled
disabled

Only one of those should be enabled, that's the one you should use as a dependency. I've input both to be on the safe side.