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?
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.
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!
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With