Inject SSH pub key to Vagrant image

Usually if you create a Vagrant VM an insecure private key gets injected into the VM, which is located at ~/.vagrant.d/insecure_private_key. In Ansible you can reference that key to ensure a passwordless login to the VM. Since Vagrant 1.8.5 this doesn’t work anymore, because of security reasons. That’s why I use now this shell provisioner with a bit Ruby code to inject my public SSH key to the VM:

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/ubuntu/.ssh/authorized_keys
    echo #{ssh_pub_key} >> /root/.ssh/authorized_keys
    apt-get -y install python-simplejson
  SHELL
end

The 2nd line is pure Ruby code. It reads the public SSH key from the default .ssh directory from the home directory and stores the content in the ssh_pub_key variable. The first 2 lines of the shell provisioner are injecting the SSH key to the authorized keys for the user ubuntu and root.

With that the VM is build together with my own public SSH key and I can login to the VM via SSH without entering a password. That makes it also super easy to handle the VM later with Ansible.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s