SSH Tunnels

General steps

  1. Install 'autossh'
  2. Install remote VM private key
  3. Connect to remote VM to establish trust
  4. Create SSH-Tunnel service file

Install 'autossh'

$ sudo apt install autossh

Install remove VM private key

$ sudo bash
# mkdir -p /etc/private
# nano /etc/private/{PrivateKeyName}.pem
Paste the content of the private key into the pem file and save.
# chmod 600 /etc/private
# chmod 600 /etc/private/{PrivateKeyName}.pem

Connect to remote VM to establish trust

$ sudo bash
# ssh -i /etc/private/{PrivateKeyName}.pem {username}@{hostname}

Create SSH-Tunnel service file

The following makes the local port 3306 available on the remote VM as port 3306.
$ sudo bash
# nano /etc/systemd/system/ssh-tunnel.service
[Unit]
Description=Persistent SSH Reverse Tunnel
After=network.target

[Service]
User=root
Environment="AUTOSSH_GATETIME=0"
ExecStart=/usr/bin/autossh               \
    -M 0                                 \
    -N                                   \
    -i /etc/private/{PrivateKeyName}.pem \
    -o "ServerAliveInterval=30"          \
    -o "ServerAliveCountMax=3"           \
    -R 3306:localhost:3306               \
    {username}@{hostname}
Restart=always
RestartSec=10

[Install]
WantedBy=multi-user.target
Activate the service:
$ sudo systemctl daemon-reload
$ sudo systemctl restart ssh-tunnel
$ sudo systemctl status  ssh-tunnel