How To Connect Virtual Machine To VS Code

How To Connect Virtual Machine To VS Code

Connecting a virtual machine (VM) such as Vagrant or EC2 instances or Droplet to Visual Studio Code (VS Code) can be a bit tricky, but with these simple steps, you'll be able to access your VM and navigate its files and directories with ease.

Prerequisite

  • Visual Studio Code.

  • Connection to the Internet.

  • A Running Virtual Machine. (i.e Ec2 instance, Droplet, Vagrant)

  1. In VS Code, click on the extension icon and search for "Remote SSH." Download and install the extension.

  1. Open the terminal on your local computer and generate an SSH key using the command.

     $ssh-keygen
    

    if you already have an existing SSH key, there's no need to generate a new one.

  2. Copy the public key to your VM using the command

    copy the public key from a windows OS

     $scp -P 22 ~/path/to/publickey user@host:~/.ssh/authorized_keys
    

    Copy the public key from a Linux OS

     $ssh-copy-id -i ~/path/to/publickey user@host
    

    Replace "user" with your username on your Virtual Machine and "host" with the IP address of the Virtual Machine

  3. Verify that your local machine can SSH into the Remote/Virtual Machine, try SSHing into the remote machine using this command below;

     $ssh user@ip-address
    
  4. In VS Code, click on the double arrowhead button in the left bottom corner.

This pops a dialog box, click Open ssh Configuration Settings from the dialog box, this gives another dialog box click on C:/user/pc-username/.ssh/config in this config file, the configuration requires a Host [name of your choice] Hostname [IP address of your remote machine] User [username on the remote machine]

please note that you can configure more than one virtual machine in the configuration file. there is no need to add the comment to your file. I am using it to explain the different virtual machines configured in this file above. Make sure to follow the proper indentation and save the file.

6. Click on the double arrowhead button again and select Connect to Host From the dialog box, select the Virtual Machine host name you want to connect, You will be prompted to select the correct OS for the remote/virtual machine.

Once the connection is established, the button in the left corner will indicate your connection to a specific host. You can now navigate the VM's files and directories just as if the Virtual Machine/instance was on your local machine.

I hope this tutorial was helpful. If you have any questions or feedback, please leave a comment below.