Search code examples
rubyherokussh-keysnet-sftp

Store SSH Key on Heroku to Connect Rails App to Remote Thru SFTP


This is a long shot, but I'm trying to add an ssh key to a Heroku for its use in connecting to another server through SFTP:

Net::SFTP.start(HOST, USER, password: PASSWORD, keys: ['yada.pem']) do |sftp|
  @sftp = sftp
end

My original solution was to push a .ssh directory to the repo and store yada.pem there. keys would include the path to this file.

A safer solution I've been told would be to store the key in an environment variable on Heroku. Problem is, this would store the key as a string, which I couldn't really pass to SFTP.start.

I could solve the problem in a couple ways:

  1. Is there a way to pass the key as a string with Ruby net/sftp?
  2. Is there a way to add a public key to Heroku so that net/sftp would use it when trying to connect to the remote server?

Thanks


Solution

  • You can pass keys as strings in the option hash under the key :key_data (should be an array of strings, each element of which containing a key in PEM format).

    Net::SFTP.start(HOST, USER, password: PASSWORD, key_data: ['PEM key as string']) do |sftp|
      @sftp = sftp
    end
    

    See Net::SSH#start (to which Net::SFTP#start defers).