0
votes

I am new to Google Cloud and am facing a challenge while adding ssh-keys to google metadata (project-wide) with gcloud command line.

When I try to add ssh-key into Google metadata (with command :: gcloud compute project-info add-metadata --metadata-from-file ssh-keys=[LIST_PATH]) along with the new ssh-key which I am trying to add, I also have to specify all existing ssh-keys in the source file. (the source file is the file where we store ssh-key value). because I will add all the ssh-keys which are present in source file so if I do not keep existing ssh-keys in source file and keep only one key, it will add only this single key into metadata and rest of the existing keys will be removed.

So what I am trying to achieve is to add any single ssh-key to the metadata without affecting existing keys. Because this will be a repeated process for many of the machines in my environment, and I cannot track existing keys every time.

1
Please read Under what circumstances may I add “urgent” or other similar phrases to my question, in order to obtain faster answers? - the summary is that this is not an ideal way to address volunteers, and is probably counterproductive to obtaining answers. Please refrain from adding this to your questions. - halfer
Moreover, please move your question to Super User (delete here, re-post there). It's off-topic here. - Martin Prikryl

1 Answers

3
votes

I've had the same question.

According to the the official doc (https://cloud.google.com/compute/docs/instances/adding-removing-ssh-keys), it is not possible to manipulate individual keys from the gcloud tool.

Here is an example shell to add a key:

gcloud compute project-info add-metadata \
  --metadata-from-file ssh-keys=<(\
    gcloud compute project-info describe --format json \
      | jq -r '.commonInstanceMetadata.items[]
               | if .key == "ssh-keys" then .value else empty end';
    echo "john:ssh-rsa mykey john")

It:

  • grabs the existing values (gcloud describe | jq).
  • adds a key (echo "john...").
  • feeds it as a pseudo-file to gcloud add-metadata.

Up to you to separate the steps, keep a local list of your keys, or whatever suits your need.

This example lacks a few features, like key de-duplication. That's just an experiment at the moment, I'll have to create a more robust script for real use.