At times while developing projects using Vagrant environments I’m making components that rely on database access. Most of the tests that I write for these components can use an in-memory database such as SQLite. However what about the times that I want to actually test the database or perhaps a ‘repository’ class that I’m writing that will interact with the database. For those purposes I just mentioned SSH tunnels comes in handy. But why do things manually when we can run Autossh at boot.

Note: For this guide I’m using systemd. If you’re using a different init system the following (systemctl) commands will be different.

Forward a Remote Port

Before we dive into Autossh, make sure the connection works as expected. Start by manually creating an SSH tunnel and forwarding port 3306 of the Vagrant box to local port 3307.

ssh -L 3307:localhost:3306 vagrant@127.0.0.1 -p 2226 -i /path/to/repo/.vagrant/machines/default/virtualbox/private_key

Add the ECDSA key to your known hosts (if needed), and verify the connection was successful. If everything went smoothly we have established that we can connect via SSH to our Vagrant box and forward port 3306 to local port 3307. Next, we will automate the process.

Create an Autossh Service

If you don’t have Autossh already installed take the opportunity to install it now. For example, in Arch Linux, sudo pacman -S autossh.

Start by creating a file named autossh.service.sample at the root of your project folder (/path/to/repo/autossh.service.sample). Add the following code to this file. I create the sample service in my project folder in order to commit this file to version control for future usage.

[Unit]
Description=AutoSSH service for port 3306
After=network.target

[Service]
Environment="AUTOSSH_GATETIME=0"
ExecStart=/usr/bin/autossh -M 0 -NL 3307:127.0.0.1:3306 -o TCPKeepAlive=yes vagrant@127.0.0.1 -p 2226 -i /path/to/repo/.vagrant/machines/default/virtualbox/private_key
User=dupkey

[Install]
WantedBy=multi-user.target

On the line starting “ExecStart” replace the “private_key” path with your own. On the next line change the “User” from “dupkey” to the user who has ownership permission of the project folder/Vagrant box.

Copy this sample file to: /etc/systemd/system/autossh.service

You may need to run sudo systemctl daemon -reload when services change.

Start the service by running sudo systemctl start autossh.service. Test the connection to verify that it works as expected. You can check the status by running sudo systemctl status autossh.service. Once you’re satisfied that everything is working correctly enable the service by running sudo systemctl enable autossh.service.


Sources: https://wiki.archlinux.org/index.php/Secure_Shell#Autossh_-_automatically_restarts_SSH_sessions_and_tunnels, https://www.everythingcli.org/ssh-tunnelling-for-fun-and-profit-autossh/