Navigation Menu

Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

SSH to AWS EC2 with Key File #15

Closed
arnoldtonderaimarunda opened this issue Feb 14, 2018 · 2 comments
Closed

SSH to AWS EC2 with Key File #15

arnoldtonderaimarunda opened this issue Feb 14, 2018 · 2 comments

Comments

@arnoldtonderaimarunda
Copy link

I was connecting to a virtual server on namecheap via SSH as follows

gateway = Net::SSH::Gateway.new(host, username,
  password: "xxxxxxxx",
  port: "21098",
  )

we have now migrated to AWS EC2 and connect to the instance using a key file *.pem. How do I use this gem with the key file to create an SSH tunnel?

Yours assistance is greatly appreciated. Many thanks

@jonn
Copy link

jonn commented Mar 9, 2018

Digging around online I found that you can specify "keys" as part of the options after host, username.

Net::SSH::Gateway.new(remote_host, remote_user, keys: ['/path/to/key.pem'])

@Genkilabs
Copy link

For those on Rails, you can use the param :key_data to put a string directly in the gateway. This means you can store your PK in the encrypted rails credentials system.

key = Rails.application.credentials.dig(:aws, :staging, :rsa_key)
gateway = Net::SSH::Gateway.new('my-ec2-endpoint', 'ec2-user', :key_data => [key], :keepalive => true)
my_new_port = gateway.open('my-serverless-aurora-db.12345.us-east-1.rds.amazonaws.com', 5432)

In the above example, this will create a port to connect ActiveRecord to a serverless postgresql aurora DB, but tunneling through a generic (unmodified) AWL Linux 2 AMI.
After that you can connect as normal on your local IP:

url: postgres://db_user:db_password@127.0.0.1:<%= my_new_port %>/database_name

The only caveat here is that if you store the PK as a string, it needs to include the \n character as appropriate. ie. your credentials should look like this when you do >rails credentials.show

aws:
  staging:
    rsa_key: "-----BEGIN RSA PRIVATE KEY-----\nMIIEpAIBAAKCAQEAnIf4....

For your own reference, you can find the full list of params in Net::SSH.start https://www.rubydoc.info/github/net-ssh/net-ssh/Net/SSH#start-class_method

...perhaps consider adding this solution in a project wiki until a better one comes along?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants