Takeshi
Takeshi

Reputation: 49

GCP VMs + ssh/config file

guys.

GCP offers multiple ways of ssh-ing in gcloud, cloud shell, and local machine cloud SDK.

While all these options are great and I have been using them, I normally prefer using .ssh/config to shorten the process of logging in to machines.

For an example, for EC2, you just add:

Host $name
    HostName $hostname
    User $username
    IdentityFile $pathtoFile

Is there any way to replicate this for GCP VMs?

Thanks

Upvotes: 4

Views: 7219

Answers (2)

Babuji Abraham
Babuji Abraham

Reputation: 67

If you want to SSH to different instances of a google cloud project (from a mac or Linux), do the following:

Step 1. Install SSH keys without password

Use the following command to generate the keys on your mac

ssh-keygen -t rsa -f ~/.ssh/<private-key-name> -C <your gcloud username>

For example private-key-name can be bpa-ssh-key. It will create two files with the following names in the ~/.ssh directory

  1. bpa-ssh-key
  2. bpa-ssh-key.pub

Step 2. Update the public key on your GCP project

Goto Google Cloud Console, choose your project, then

VMInstances->Metadata->SSH Keys->Edit->Add Item

Cut and paste the contents of the bpa-ssh-key.pub (from your mac) here and then save

Reset the VM Instance if it is running

Step 3. Edit config file under ~/.ssh on your mac Edit the ~/.ssh/config to add the following lines if not present already

Host *
PubKeyAuthentication yes
IdentityFile ~/.ssh/bpa-ssh-key

Step 4. SSHing to GCP Instance

ssh username@gcloud-externalip

It should create a SSH shell without asking for the password (since you have created the RSA/SSH keys without a password) on the gcloud instance.

Since Metadata is common across all instances under the same project, you can seam-lessly SSH into any of the instances by choosing the respective External IP of the gcloud instance.

Upvotes: -1

Phakin
Phakin

Reputation: 123

According to This Doc

If you have already connected to an instance through the gcloud tool, your keys are already generated and applied to your project or instance. The key files are available in the following locations:

  • Linux and macOS
    • Public key: $HOME/.ssh/google_compute_engine.pub
    • Private key: $HOME/.ssh/google_compute_engine
  • Windows
    • Public key: C:\Users[USERNAME].ssh\google_compute_engine.pub
    • Private key: C:\Users[USERNAME].ssh\google_compute_engine

You can use the key with typical -i or in .ssh/config config file.

Or simply do

ssh-add ~/.ssh/google_compute_engine

to add the identity to your ssh agent.

PS> I've seen people create an alias for the ssh command, something like

alias gce='gcloud compute ssh'

Upvotes: 0

Related Questions