如何使用terraform将ssh密钥添加到GCP实例?

时间:2016-07-28 19:18:59

标签: ssh google-cloud-platform terraform

所以我有一个在Google Cloud Platform中创建实例的terraform脚本,我希望能够让我的terraform脚本也将我的ssh密钥添加到我创建的实例中,以便我可以通过ssh配置它们。这是我目前的terraform脚本。

#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 {}
  }
}

我必须添加什么才能让我的terraform脚本添加我的ssh密钥/Users/myUsername/.ssh/id_rsa.pub

6 个答案:

答案 0 :(得分:20)

我认为这样的事情应该有效:

  metadata {
    sshKeys = "${var.gce_ssh_user}:${file(var.gce_ssh_pub_key_file)}"
  }

https://cloud.google.com/compute/docs/instances/adding-removing-ssh-keys描述了元数据机制,我在https://github.com/hashicorp/terraform/issues/6678

找到了这个示例

答案 1 :(得分:5)

仅作记录。从0.12开始,该块看起来应该像:

resource "google_compute_instance" "default" {
  # ...

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

  # ...
}

(请注意,=标记后面应加上metadatassh-keyssshKeys之比。)

答案 2 :(得分:3)

您可以使用以下

metadata = {
  ssh-keys = "username:${file("username.pub")}"
}

我正在努力使用terraform使用ssh密钥创建实例,并且此答案也已通过测试并可以正常工作。

答案 3 :(得分:2)

如果您想要多个键,可以像这样使用heredoc

  metadata = {
    "ssh-keys" = <<EOT
<user>:<key>
<user>:<key>
EOT
  }

terraform fmt提供给我的帖子中,我保留了奇怪的格式。

答案 4 :(得分:0)

这里经过测试。

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

答案 5 :(得分:0)

只需更新 Terraform v0.15.4 中的多个键:

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

并根据变量:

variable "ssh_keys" {
  type = list(object({
    publickey = string
    user = string
  }))
  description = "list of public ssh keys that have access to the VM"
  default = [
      {
        user = "username"
        publickey = "ssh-rsa yourkeyabc username@PC"
      }
  ]
}