How to SSH to Google Cloud VM instance on command line
If you want to connect to a Google Cloud VM instance (my-instance
in this example) from your command line using SSH, you have two options:
Directly connect using gcloud
This will always work if your instance has SSH enabled, even if it does not have an external IP:
gcloud compute ssh my-instance --zone $(gcloud compute instances list --filter="name=my-instance" --format "get(zone)" | awk -F/ '{print $NF}')
Note that your have to replace my-instance by your actual instance name two times in the command above. The subcommand (enclosed in $(...)
) finds the correct zone for your instance since at the time of writing this article gcloud compute ssh
will not work unless you set the correct zone for that instance. SeeĀ How to find zone of Google Cloud VM instance on command line for more details.
Connect using external IP
You can also use gcloud
to get the external IP and connect to it using your standard SSH client.
ssh $(gcloud compute instances list --filter="name=my-instance" --format "get(networkInterfaces[0].accessConfigs[0].natIP)")
This has the added advantage that your will be able to use this in other SSH-like command like rsync
.
For reference also see the official manual on Securely Connecting to Instances