title: How to pass a key file when spawning an ssh command from node.js?
body: <p>This works from my local terminal: </p>
  
  <pre><code>ssh -i ~/.ec2/mykey.pem ubuntu@ec2-yada-yada.amazonaws.com ls
  </code></pre>
  
  <p>Of course it does. But when I try the same using node.js' <code>child_process.spawn</code> command it complains that the key does not exist / can't be accessed.</p>
  
  <pre><code>// child process
  var childProcess = require('child_process').spawn;
  
  // spawn the slave using slaveId as the key
  slaves[slaveId] = childProcess('ssh', [
      '-i /mykey.pem',
      'ubuntu@ec2-yada.amazonaws.com',
      'ls'
  ])  
  </code></pre>
  
  <p>Result:</p>
  
  <pre><code>stderr: Warning: Identity file  /mykey.pem not accessible: No such file or directory.  
  stderr: Permission denied (publickey).
  </code></pre>
  
  <p>Things tried:</p>
  
  <ol>
  <li><p>Variations on the path to key:<br>
  <code>/actual/path/to/mykey.pem</code><br>
  <code>mykey.pem</code> (with a copy of the file in the root of the node project)<br>
  <code>/mykey.pem</code> (with a copy of the file in the root of the node project)<br>
  <code>~/.ec2.mykey.pem</code> (where it should be)  </p></li>
  <li><p>Running the command without the ssh part, ie. <code>childProcess(ls);</code> - works.</p></li>
  <li><p><code>chmod 644, 600, 400 etc. mykey.pem</code></p></li>
  </ol>
  
  <p>My only theory at this point is there is an issue with passing a file reference in and I need to do <em>something</em> using the fs module. (?) And yes, I know there are libraries out there for ssh access with node but they use passwords which won't cut it and anyway, my requirements don't really justify a library.</p>
  
  <p>Please tell me I'm being stupid and that this is possible. </p>
  
  <p><strong>UPDATE:</strong>  </p>
  
  <p>OK, so I <em>can</em> use the exec command like this:  </p>
  
  <pre><code>var childProcess = require('child_process').exec;
  slaves[slaveId] = childProcess('ssh -i mykey.pem ubuntu@ec2-yada.amazonaws.com ls',  function (error, stdout, stderr) {...}
  </code></pre>
  
  <p>Still, I feel like I've been downgraded from creating a true slave using <code>fork</code> with all it's nice messaging and handy properties (my original implementation which runs fine locally) to having a vacuum cleaner and being told to do all the work myself (now that I want to launch slaves on remote hosts).</p>