How to ssh into vagrant without using vagrant SSH?

I have been using vagrant for quite some time on my development laptop for work as well as for learning purposes. But one thing which I noticed working with Vagrant is you have to use vagrant ssh every time whenever you want to login into your virtual machine and in case if you have multiple virtual machine configured into your Vagrantfile then you have to put down the config.vm.hostname along with vagrant ssh command for example vagrant ssh myvirtualmachine.

I have been wondering is there another way with which I can ssh into my virtual machine instead of using vagrant ssh?

In this blog post we will look around different ways to replace vagrant ssh command -

  1. Using vagrant ssh-config and private key
  2. Using shorthand vagrant ssh-config

1. Using vagrant ssh-config and private key

The first way would be to use the vagrant ssh-config utility along with the private key.

So to start with the first command which we need to run is -

1vagrant ssh-config

(*Note - Make Sure your vagrant box is up and running)

After running the above command it should generate the following output -

 1Host testserver
 3User vagrant
 4Port 2222
 5UserKnownHostsFile /dev/null
 6StrictHostKeyChecking no
 7PasswordAuthentication no
 8IdentityFile /Users/rahul/virtualmachine1/.vagrant/machines/elkserver/virtualbox/private_key
 9IdentitiesOnly yes
10LogLevel FATAL

Now we are going to use the private_key which we just generated and present at /Users/rahul/virtualmachine1/.vagrant/machines/elkserver/virtualbox/private_key.

Run the ssh command using the private key -

1ssh -i /Users/rahul/virtualmachine1/.vagrant/machines/elkserver/virtualbox/private_key -o PasswordAuthentication=no vagrant@ -p 3150

2. Using shorthand vagrant ssh-config

In the previous step we have seen how to generate the private_key and use the same private_key to ssh into a virtual machine.

But if you take the previous example from a usability perspective then a developer like me would not be interested in running those commands again and again on a daily basis just to ssh into the virtual machine.

So can we shorten the previous command?

Here is the short version of the same command if you are using on single host -

1ssh $(vagrant ssh-config | awk 'NR>1 {print " -o "$1"="$2}') localhost

In case if you have multiple host then you can use the following version of the command -

2ssh $(vagrant ssh-config $HOST | sed '/^[[:space:]]*$/d' |  awk 'NR>1 {print " -o "$1"="$2}') localhost

If you look at the above command carefully then we first trying to set the hostname into the HOST variable and using the same into the ssh command.

Here are few more discussion from the stackoverflow

Read More -

  1. How to ssh int vagrant without using "vagrant SSH"?
  2. 4 Ways to Add SSH public key to Vagrant VM(Virtual Machine)?