Using the SSH command to access a Vagrant machine
Guillaume Briday
1 minute
If you regularly use Vagrant, you know that to access the virtual machine, you need to use the command:
$ vagrant ssh
Without much explanation, Vagrant connects us to the virtual machine as the user vagrant
.
However, if a private network is defined and you know the IP address of the virtual machine, you might try to connect using the vagrant
user:
For instance, with a configuration like this:
Vagrant.configure("2") do |config|
config.vm.network "private_network", ip: "192.168.50.4"
end
The SSH command would be:
$ ssh [email protected]
But you will encounter an error. For some reason, in this case, the vagrant
user fails to connect.
To connect to the virtual machine via vagrant ssh
, Vagrant uses SSH keys and a specific port. I've already covered this in the article: Connecting to a Remote Server via SSH if you're unfamiliar with this process.
We can use this private key to override the default SSH configuration and use it with the standard SSH command.
To retrieve the SSH configuration details for the specific machine, use the following command:
$ vagrant ssh-config
Host default
HostName 127.0.0.1
User vagrant
Port 2200
UserKnownHostsFile /dev/null
StrictHostKeyChecking no
PasswordAuthentication no
IdentityFile /Users/guillaumebriday/Sites/demo/.vagrant/machines/default/virtualbox/private_key
IdentitiesOnly yes
LogLevel FATAL
Vagrant displays the configuration it uses. Since we know the machine's IP address and the path to its private key, we can edit the ~/.ssh/config
file to add a configuration:
Host 192.168.50.4
User vagrant
Port 22
UserKnownHostsFile /dev/null
StrictHostKeyChecking no
PasswordAuthentication no
IdentityFile /Users/guillaumebriday/Sites/demo/.vagrant/machines/default/virtualbox/private_key
IdentitiesOnly yes
LogLevel FATAL
Now we can connect using the standard ssh
command:
$ ssh 192.168.50.4
This configuration will ensure the correct private key is used, and the connection will be successfully established!
It's no longer necessary to specify the vagrant
user in the command since it's already defined in the ~/.ssh/config
file.
In my case, I needed to perform this configuration to manually run Ansible scripts instead of relying on the Ansible Provisioner.
Thank you!