How can I update (not overwrite) ssh_keys in project metadata?

I am using the google_compute_project_metadata resource like so:

resource "google_compute_project_metadata" "default" {
  metadata = {
ssh-keys = join("\n", [for user, key in local.vars.project_ssh_keys : "${user}:${file(key)}"])
  }
}

I am doing this to provision an ssh key for ansible when creating instances and it works but it wipes out any other keys that are dynamically added via gcloud cli or gcp console access.

I’d like to be able to only add the ansible key if it’s missing without wiping out all the other keys. There doesn’t appear to be a data resource for project metadata but I can see when running tf plan that tf is aware if there are other keys because it just removes the keys that I don’t explicitly have defined in local.vars

Has anyone had to solve this particular need before? I suspect that I could potentially pull in the metadata some other way and loop over it to only check if the ansible key exists but I’m fairly new to terraform and not quite fluent on looping and conditionals within Terraform itself.

You could set metadata on the google_compute_instance instead. If you so desired you could update the metadata after provisioning to remove that SSH key for added security.