Command or Shell task hangs when using ssh to create a tunnel

ansibleconfiguration-managementssh-tunnelubuntu-13.04

I am using Ansible to push configuration. I have a task inside a playbook that I want to start an ssh tunnel in the background for MongoDB. The task command that i'm using is

- name: Start tunnel service
  shell: ssh -f -N -L 27018:localhost:27017 mongo@remote-server 

But no matter what I do I cannot get ansible to continue. Instead it hangs or acts like it is waiting on something to return a response. If I run this command in the shell like normal it doesn't have any problems and I can connect to the remote mongo instance.

At first I thought because I was setting up a new server that ssh's known_hosts were waiting for a user to respond yes/no before moving on. In this case I tried two options. First I tried adding the server's fingerprint to the known_hosts file. After running from the shell it didn't asked for a known_hosts entry, but ansible also is still hanging. I also tried the option of

ssh -o StrictHostKeyChecking=no -f -N -L 27018:localhost:27017 mongo@remote-server

But this option is also producing the same problem with ansible hanging.

I have tried switching between ansible's command and shell module without any change to the problem. My most recent experiment was to try nohup before the command, but this isn't working either.

nohup ssh -f -N -L 27018:localhost:27017 mongo@remote-server

Also trying to get creative thinking that if a different process was able to run the command that afterwards it would send a response back to ansible, I tried wrapping it as an Upstart task. I placed the shell command inside a /etc/tunnel.sh file and also put the upstart script in /etc/init/tunnel.conf. But this also doesn't work and seems to have trouble actually starting the script. If I run sudo service tunnel start it will start but has trouble stopping. Though running this through ansible as a command doesn't do anything and just sits there and hangs like all the other experiments.

- name: Start tunnel service
  command service tunnel start

Best Answer

If you're using sudo and a key I would wager you're not preserving the SSH_AUTH_SOCK environment variable. This will be required in order to establish a connection from the orchestrated machine to the mongodb instance. In this situation you should add something like the following to /etc/sudoers:

Defaults        env_keep+=SSH_AUTH_SOCK
Defaults        env_reset