Add SSH Public Key to Vagrant

serhatteker

Serhat Teker

Posted on January 18, 2021

Add SSH Public Key to Vagrant

You can access your Vagrantbox via:

$ vagrant ssh
Enter fullscreen mode Exit fullscreen mode

However if you want to access it via usual ssh cli, how can you do that?

By default Vagrant binds your localhost's 2222 port to your Vagrantbox's 22 port.

So you can access your box by;

$ ssh -p 2222 vagrant@localhost
Enter fullscreen mode Exit fullscreen mode

It is same thing as vagrant ssh.

But before you can do that you need to add your ssh pub_key to your vagrant host.

ssh-copy-id

The best way to add your pub_key is to use ssh-copy-id binary/command:

$ ssh-copy-id -i ~/.ssh/id_rsa.pub -p 2222 vagrant@localhost
/usr/bin/ssh-copy-id: INFO: Source of key(s) to be installed: "/home/<username>/.ssh/id_rsa.pub"
/usr/bin/ssh-copy-id: INFO: attempting to log in with the new key(s), to filter out any that are already installed
/usr/bin/ssh-copy-id: INFO: 1 key(s) remain to be installed -- if you are prompted now it is to install the new keys
vagrant@localhost's password:
Enter fullscreen mode Exit fullscreen mode

After you prompt your vagrant user password, pub_key will be appended.

Number of key(s) added: 1

Now try logging into the machine, with:   "ssh -p '2222' 'vagrant@localhost'" and check to make sure that only the key(s) you wanted were added.
Enter fullscreen mode Exit fullscreen mode

INFO
Default credentials are:

  • user: vagrant
  • password: vagrant

Other Methods

You can use some manual unix cli magic:

$ cat ~/.ssh/id_rsa.pub | ssh -i ~/.ssh/id_rsa.pub -p 2222 vagrant@localhost 'cat >> .ssh/authorized_keys && echo "SSH key copied."'
Enter fullscreen mode Exit fullscreen mode

Or, you can use Vagrant's provision:

Vagrant.configure(2) do |config|
  config.vm.provision "shell", inline: <<-SHELL
    cat /home/<username>/.ssh/id_rsa.pub >> /home/vagrant/.ssh/authorized_keys
SHELL
end
Enter fullscreen mode Exit fullscreen mode

Now you can access your Vagrantbox via ssh without password:

$ ssh -i ~/.ssh/id_rsa.pub -p 2222 vagrant@localhost
Enter fullscreen mode Exit fullscreen mode

All done!

💖 💪 🙅 🚩
serhatteker
Serhat Teker

Posted on January 18, 2021

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related

Add SSH Public Key to Vagrant
ssh Add SSH Public Key to Vagrant

January 18, 2021