Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I add my own public key to Vagrant VM?

I got a problem with adding an ssh key to a Vagrant VM. Basically the setup that I have here works fine. Once the VMs are created, I can access them via vagrant ssh, the user "vagrant" exists and there's an ssh key for this user in the authorized_keys file.

What I'd like to do now is: to be able to connect to those VMs via ssh or use scp. So I would only need to add my public key from id_rsa.pub to the authorized_keys - just like I'd do with ssh-copy-id.

Is there a way to tell Vagrant during the setup that my public key should be included? If not (which is likely, according to my google results), is there a way to easily append my public key during the vagrant setup?

like image 636
tehK Avatar asked May 06 '15 11:05

tehK


People also ask

How do I add a public key to my repository?

Add the public key to your repositoryClick Access keys from the left menu. Press Add key. From the Add SSH key dialog, enter a Label and paste the public key from the clipboard. Press Add key.

How do I ssh into vagrant machine?

Simply CMD-SHIFT-P then "Remote-SSH: Connect to Host..." and the ssh . config entry you just added is automatically listed - you simply select it and voila, vscode connects to your remote vagrant vm!


2 Answers

You can use Ruby's core File module, like so:

  config.vm.provision "shell" do |s|     ssh_pub_key = File.readlines("#{Dir.home}/.ssh/id_rsa.pub").first.strip     s.inline = <<-SHELL       echo #{ssh_pub_key} >> /home/vagrant/.ssh/authorized_keys       echo #{ssh_pub_key} >> /root/.ssh/authorized_keys     SHELL   end 

This working example appends ~/.ssh/id_rsa.pub to the ~/.ssh/authorized_keys of both the vagrant and root user, which will allow you to use your existing SSH key.

like image 116
Meow Avatar answered Sep 30 '22 14:09

Meow


Copying the desired public key would fall squarely into the provisioning phase. The exact answer depends on what provisioning you fancy to use (shell, Chef, Puppet etc). The most trivial would be a file provisioner for the key, something along this:

config.vm.provision "file", source: "~/.ssh/id_rsa.pub", destination: "~/.ssh/me.pub" 

Well, actually you need to append to authorized_keys. Use the the shell provisioner, like so:

Vagrant.configure(2) do |config|   # ... other config   config.vm.provision "shell", inline: <<-SHELL     cat /home/vagrant/.ssh/me.pub >> /home/vagrant/.ssh/authorized_keys   SHELL   # ... other config end 

You can also use a true provisioner, like Puppet. For example see Managing SSH Authorized Keys with Puppet.

like image 31
Remus Rusanu Avatar answered Sep 30 '22 15:09

Remus Rusanu