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?
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.