Pages

Monday, August 8, 2016

Vagrant auto SSH Keys

There are many cases where when we configure the vagrant machine we also need to push the ssh keys to the newly created machine. While using Ansible, the ping command works only when the ssh keys are available on the remote machine.

Vagrant does provide ways to copy the ssh keys from host machine to the remote machine (guest) when creating them.

Add the below content to the Vagrantfile as

if File.exists?(File.join(Dir.home, ".ssh" , "id_rsa.pub"))
     ssh_key= File.read(File.join(Dir.home, ".ssh","id_rsa.pub"))
  
      config.vm.provision :shell, :inline =>"
          echo 'Copying Local Ssh Keys to the VM For Provisioning'
          mkdir -p /home/vagrant/.ssh
          chmod -R 750 /home/vagrant/.ssh
          echo '#{ssh_key}' >> /home/vagrant/.ssh/authorized_keys && chmod -R 644 /home/vagrant/.ssh/authorized_keys          
           ", privileged: false
  else
      raise Vagrant::Errors::VagrantError, "\n SSH keys Not Found"
  end

The whole vagrantfile looks as ,

[root@puppet sshkeys]# cat Vagrantfile
Vagrant.configure(2) do |config|
   config.vm.box = "geerlingguy/centos7"
   config.vm.host_name = "sshdev.foohost.vm"

   config.vm.provider :virtualbox do |vb|
       vb.name = "SSHFooBarhost" #Name of the Virtual
       vb.customize ["modifyvm", :id , "--cpus", 4]
   end

   if File.exists?(File.join(Dir.home, ".ssh" , "id_rsa.pub"))
      ssh_key= File.read(File.join(Dir.home, ".ssh","id_rsa.pub"))
     
           config.vm.provision :shell, :inline =>"
           echo 'Copying Local Ssh Keys to the VM For Provisioning'
           mkdir -p /home/vagrant/.ssh
           chmod -R 750 /home/vagrant/.ssh
           echo '#{ssh_key}' >> /home/vagrant/.ssh/authorized_keys && chmod -R 644 /home/vagrant/.ssh/authorized_keys          
           ", privileged: false
  else
      raise Vagrant::Errors::VagrantError, "\n SSH keys Not Found"
  end

end

Upon running the “vagrant up” ,it not only starts the guest machine but also provisions us with the ssh keys of the host machine to the guest machine.


More to Come. Happy learning J

1 comment :

  1. Your file permissions are wrong.
    You need 600 for id_rsa and id_rsa.pub

    ReplyDelete