Access GCP VMs from Your Local Terminal

ยท

3 min read

Google Cloud Platform (GCP) offers powerful infrastructure capabilities through its Virtual Machines (VMs). Accessing these VMs securely from your local terminal requires setting up SSH access. This guide will walk you through how to use your local terminal to connect to a GCP VM by adding your SSH public key to the VM metadata.

Prerequisites

Before we begin, ensure you have the following:

  1. Google Cloud SDK (gcloud CLI) installed on your local machine. You can install it here.

  2. SSH key pair generated on your local machine. If you don't have one, you can create it using the command (replace KEY_FILENAME and USERNAME)

     ssh-keygen -t rsa -f ~/.ssh/KEY_FILENAME -C USERNAME -b 2048
    
  3. GCP account with appropriate permissions to create and manage VMs.

Step-by-Step Guide

Step 1: Create a New VM Instance

First, let's create a new VM instance. You can do this through the GCP Console or using the gcloud command:

gcloud compute instances create my-vm \
    --zone=us-central1-a \
    --machine-type=e2-medium \
    --image-family=debian-11 \
    --image-project=debian-cloud

Replace my-vm, us-central1-a, and other parameters with your preferred instance name, zone, machine type, and image.

Step 2: Add Your SSH Public Key to VM Metadata

Once your VM is created, you'll need to add your SSH public key to the VM's metadata so you can access it.

The above configuration adds your SSH public key to the instance metadata, allowing you to log in as the specified user.

Step 3: Connect to the VM via SSH

Now that your public key is added to the VM metadata, you can SSH into the VM using the following command:

ssh -i ~/.ssh/PRIVATE_KEYFILE username@<VM-EXTERNAL-IP>

This command establishes an SSH connection from your local terminal to the GCP VM. Replace PRIVATE_KEYFILE and username with your actual username and VM's external IP address.

Step 4: Verify Your Connection

Once connected, you should see a terminal prompt for your VM, indicating a successful SSH connection. You can now manage your VM just like you would with any other remote server.

Troubleshooting Tips

  • Check Firewall Rules: Ensure that your VM's firewall rules allow SSH connections (TCP port 22). You can manage firewall rules via the GCP Console or the gcloud command.

  • Metadata Propagation: Sometimes, metadata changes take a few minutes to propagate. If you encounter issues, wait a few minutes and try connecting again.

  • Public Key Format: Ensure your public key is in the correct format, typically starting with ssh-rsa.

Conclusion

By following these steps, you can securely access your GCP VMs from your local terminal using SSH keys. This method provides a convenient and secure way to manage your instances without needing to enter passwords, streamlining your workflow and enhancing security and if you are not a fan of using the in-browser ssh session.

ย