Linux – How to launch a SSH tunnel with upstart

linuxsshupstart

I am not very used to sys admin and recently created an SSH tunnel between two servers (on Ubuntu 12.4) with the following command:

ssh -fNg -L 3307:127.0.0.1:3306 tunneluser@xx.xx.xx.xx

It worked, I also added this command to /etc/rc.local, and it successfully launch the SSH tunnel at startup.
However, I tried to add my tunnel in a file in /etc/init/my_tunnel.conf, and it worked but launched nearly 12 tunnels at every startup! I used the following code:

start on (local-filesystems and net-device-up IFACE=eth0)
stop on runlevel[016]
respawn
exec ssh -fNg -L 3307:127.0.0.1:3306 tunneluser@xx.xx.xx.xx
exit 0

I spent hours on this and do not understand at all why and how this script is executed so many times. I also tried start on[2345], completely read upstart's manual but still the same. I am sure that I am missing something here.

If someone can help me.
Thanks.

Best Answer

As c4f4t0r commented, respawn will run the command again when the script exits. By using -f it runs in the background, effectively exiting and causing upstart to respawn it. If you remove -f then it will remain in a running state that upstart can observe when it unexpectedly exits.

start on (local-filesystems and net-device-up IFACE=eth0)
stop on runlevel[016]
respawn
exec ssh -Ng -L 3307:127.0.0.1:3306 tunneluser@xx.xx.xx.xx
exit 0