title: How can I connect to my EC2 Instance via SSH with an AWS Lambda Function?
body: <p>I'm attempting to ssh into an ec2 instance with a lambda function. I keep receiving a null value for my response every time I try run my function with my logs displaying the following error:</p>
  
  <pre><code>START RequestId: xxxx-xxxx-xxxx-xxxx-xxxx Version: $LATEST
  2020-02-19T22:56:16.574Z    xxxx-xxxx-xxxx-xxxx-xxxx    INFO    failed connection, boo
  2020-02-19T22:56:16.576Z    xxxx-xxxx-xxxx-xxxx-xxxx    INFO    Error: Timed out while waiting for handshake
      at Timeout._onTimeout (/var/task/node_modules/ssh2/lib/client.js:687:19)
      at listOnTimeout (internal/timers.js:531:17)
      at processTimers (internal/timers.js:475:7) {
    level: 'client-timeout'
  }
  </code></pre>
  
  <p>With it being a timed out error, I figured it was an issue with connecting to the instance rather than my code, but the lambda is apart of the same VPC that the EC2 is apart of, along with a security group enabling ssh connections. I'm also able to connect to ssh into the instance manually as well.</p>
  
  <pre><code>exports.handler = async (event) =&gt; {
  
    const fs = require('fs')
    const SSH = require('simple-ssh');
    const pemfile = 'xxx.pem';
    const user = 'ec2-user';
    const host = 'xx.xx.xx.xx';
  
  
    // all this config could be passed in via the event
    const ssh = new SSH({
      host: host,
      user: user,
      key: fs.readFileSync(pemfile)
    });
  
    let cmd = "ls";
    if (event.cmd == "long") {
      cmd += " -l";
    }
  
    let prom = new Promise(function(resolve, reject) {
  
      let ourout = "";
  
      ssh.exec('mkdir /home/ec2-user/ssh_success', {
        exit: function() {
          ourout += "\nsuccessfully exited!";
          resolve(ourout);
        },
        out: function(stdout) {
          ourout += stdout;
        }
      }).start({
        success: function() {
          console.log("successful connection!");
        },
        fail: function(e) {
          console.log("failed connection, boo");
          console.log(e);
        }
      });
  
    });
  
    const res = await prom;
  
    const response = {
      statusCode: 200,
      body: res,
    };
    return response;
  };
  </code></pre>