Skip to main content

Copy custom SSH key into VM

Sometimes it is more useful to copy the user's public key into a VM and have access to the VM with the default user key.

In this example, the user's public key from "#{Dir.home}/.ssh/id_ed25519.pub" will be copied to authorized_keys in vm.

Vagrantfile
# -*- mode: ruby -*-
# vi: set ft=ruby :

Vagrant.configure("2") do |config|

config.vm.provision "shell" do |s|
ssh_pub_key = File.readlines("#{Dir.home}/.ssh/id_ed25519.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

config.vm.define "example-vm-1" do |ev1|
# ...
end
end