I am trying to connect VSCode to my GCP instances but am unable to. From a terminal, I can ssh into the machines with gcloud compute ssh my_machine_name
but I'm not sure how to translate that into what VSCode Remote-SSH is looking for. When I created the config in VSCode I did this:
Host my_machine_name
HostName my_machine_name
User me@my_company.com
But the HostName is wrong because it's just the name of the machine and not the full HostName or IP address. I haven't even told VSCode that it's a GCP instance. How do I find the HostName? I imagine there's a connection between my_machine_name
and the true HostName somewhere in my configs, but I can't find it. I found a GCP-Service.json file with the following keys:
{
"type":
"project_id":
"private_key_id":
"private_key":
"client_email":
"client_id":
"auth_uri":
"token_uri":
"auth_provider_x509_cert_url":
"client_x509_cert_url":
}
but I don't see anything that looks like a HostName or IP address.
Just to see, I tried to connect and got the following error:
Could not establish connection to "my_machine_name": Permission denied (publickey).
(Note sure if this is relevant but sometimes when I first try to connect I get the following, but after I click "Retry" it goes back to the publickey message again):
"Could not establish connection to "my_machine_name": Remote host key has changed, port forwarding is disabled."
So I tried to add a private key like so:
Host my_machine
HostName my_machine
User user@my_company.com
IdentityFile ~/.ssh/id_rsa
I also tried the private key from my GCP-Service.json file as well but got the same result. What am I supposed to do to connect VSCode to my GCP instance?
Simply running gcloud compute config-ssh
, and you would get example-instance.us-central1-a.MY-PROJECT
in your vs code ssh targets. Details at config-ssh
Per my comment, this is straightforward and worked for me.
Assuming:
PROJECT=[[YOUR-PROJECT]]
INSTANCE=[[YOUR-INSTANCE]]
ZONE=[[YOUR-ZONE]]
This is slightly hacky but either:
USER=$(\
gcloud compute ssh ${INSTANCE} \
--zone=${ZONE} \
--project=${PROJECT} \
--command "whoami") && echo ${USER}
Or:
gcloud auth list --format="value(account)"
[[USER]]@[[DOMAIN]]
And:
IP=$(\
gcloud compute instances describe ${INSTANCE} \
--zone=${ZONE} \
--project=${PROJECT} \
--format='value(networkInterfaces[0].accessConfigs[0].natIP)') && echo ${IP}
NOTE the above assumes a single network interface and a public IP
Then, replacing the values with the above:
Host compute_engine
HostName [[IP]]
IdentityFile ~/.ssh/google_compute_engine
User [[USER]]
Port 22
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With