October 16, 2020

Setting up autossh autostart with systemd

autossh systemd

Just a quick note on setting up autossh on system’s startup. I use it to proxy-forward traffic from the internet exposed host to a firewalled host inside a private network. This way all the data and apps stay on-prem but are available to external users if needed.

autossh advantage is that it restart ssh in case connection breaks for some reason. It’s important to configure it in a way so that it can detect such breakdowns. For non-critical services, I specify the following options:

-o "ExitOnForwardFailure=yes" -o "ServerAliveInterval 30" \ 
-o "ServerAliveCountMax 3"

That makes autossh detect issues within 2 minutes – enough for my purposes. The rest of parameters I provide are disabling autossh monitoring mechanism (-M 0 because it’s not very reliable), sending it to the background (-f, if running from command line) and the standard ones to set up ssh tunnel. Here’s an example:

autossh -M 0 -f -o "ExitOnForwardFailure=yes" \
                -o "ServerAliveInterval 30" \
                -o "ServerAliveCountMax 3" \
                -NR 8088:127.0.0.1:80 -i <ssh_key> user@host

To get this command execute on system’s boot, we need to create a simple systemd service file /etc/systemd/system/autossh-<host>-<service/port>.service:

[Unit]
Description=Keeps a tunnel to <host> for <service/port> open
After=network.target

[Service]
User=<user>
ExecStart=/usr/bin/autossh -M 0 -o "ExitOnForwardFailure=yes" \
                                -o "ServerAliveInterval 30" \
                                -o "ServerAliveCountMax 3" \
                                -NR 8088:127.0.0.1:80 \
                                -i <ssh-key>
                                user@host

[Install]
WantedBy=multi-user.target

and activate it: systemctl enable autossh-<host>-<service/port>.


— `If you knew Time as well as I do,' said the Hatter, `you wouldn't talk about wasting IT. It's HIM.'
$ Last updated: Oct 17, 2020 at 18:09 (EEST) $