How to add ssh key to a GCP instance using terraform?

So, I have a terraform script that creates instances in the Google Cloud platform, I want my terraform script to also add my ssh key to the instances so that I can provide them via ssh. Here is my current terraform script.

#PROVIDER INFO provider "google" { credentials = "${file("account.json")}" project = "myProject" region = "us-central1" } #MAKING CONSUL SERVERS resource "google_compute_instance" "default" { count = 3 name = "a-consul${count.index}" machine_type = "n1-standard-1" zone = "us-central1-a" disk { image = "ubuntu-1404-trusty-v20160627" } # Local SSD disk disk { type = "local-ssd" scratch = true } network_interface { network = "myNetwork" access_config {} } } 

What do I need to add to this so that my terraform script add my ssh key /Users/myUsername/.ssh/id_rsa.pub ?

+10
source share
3 answers

I think something like this should work:

  metadata = { ssh-keys = "${var.gce_ssh_user}:${file(var.gce_ssh_pub_key_file)}" } 

https://cloud.google.com/compute/docs/instances/adding-removing-ssh-keys describes the metadata mechanism, and I found this example at https://github.com/hashicorp/terraform/issues/6678

+21
source

One thing is checked here.

  metadata { sshKeys = "${var.ssh_user}:${var.ssh_key} \n${var.ssh_user1}:${var.ssh_key1}" } 
+2
source

For recording only. Starting from 0.12, the block should look like this:

 resource "google_compute_instance" "default" { # ... metadata = { ssh-keys = join("\n", [for user, key in var.ssh_keys : "${user}:${key}"]) } # ... } 

(note the = sign after the metadata token and ssh-keys against sshKeys ).

+2
source

All Articles