How do you securely retrieve the ssh host keys from a google compute engine instance?

I want to update my ~/.ssh/known_hosts with the host key information for a newly created GCE instance. But I'm not sure how to securely retrieve that information.

I thought something like

gcloud compute ssh <GCEUSER>@<GCEHOST> --command='ssh-keyscan 127.0.0.1'

might work. But that (per the gcloud compute ssh documentation) appears to just be a wrapper for ssh (and, based on seeing StrictHostKeyChecking=no in the parameters listed in the associated log file under $HOME/.config/gcloud/logs/, apparently isn't doing any sort of checking on the host's identity).

There does seem to be a way to use the web console to launch a browser-based ssh session (and interactively/manually run ssh-keyscan), but 1) I can't see the internals to know if it really is as secure as it should be and 2) isn't an effective API for script integration.

Is there an API/gcloud mechanism for securely retrieving the GCE instance's host key?


Solution 1:

OP linked to bug 35907612 (initially mentioned by Rahi) which was marked “fixed” with a link to the documentation Storing host keys.

To get the host key, you need to enable “guest attributes” before or during creation of the GCE instance. I enabled it project-wide (not sure why it was disabled by default). Alternatively, you have a chance to enable it when you create the instance.

According to the documentation, gcloud is required to populate the guest attributes, but I seem to be able to jump to step “Confirming that host keys are stored as guest attributes” right after the instance boots up.

notes

  1. In Step 2 (confirming keys), I chose Option 2, because I didn’t ask gcloud to populate ~/.ssh/google_compute_known_hosts in last step, so I want to see the keys, not just verifying that they are “somewhere”.

  2. When you run get-guest-attributes sub-command, both --project and --zone flags are optional, and they default to the configuration set with gcloud config.

  3. To get the SHA-256 hash for host keys directly from get-guest-attributes, with help of jq:

    gcloud compute instances get-guest-attributes my-instance --format json | jq -r '.[] | "\(.key) \(.value) my-server-name"' | ssh-keygen -l -f -
    

    Explain: -r means --raw-output in jq. -l means listing keys with hashes. -f - means file from stdin. my-server-name is optional comment that appears in output (otherwise you'll see no comment).