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

Ale*_*hen 12 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 {}
  }
}
Run Code Online (Sandbox Code Playgroud)

为了让我的terraform脚本添加我的ssh密钥,我需要添加/Users/myUsername/.ssh/id_rsa.pub什么?

mbl*_*ele 22

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

  metadata = {
    ssh-keys = "${var.gce_ssh_user}:${file(var.gce_ssh_pub_key_file)}"
  }
Run Code Online (Sandbox Code Playgroud)

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

  • 嗨,小心点,现在不赞成使用sshKeys,并且当前语法是ssh-keys。 (5认同)

sam*_*bit 7

您可以使用以下内容

metadata = {
  ssh-keys = "username:${file("username.pub")}"
}
Run Code Online (Sandbox Code Playgroud)

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


小智 5

这是经过测试的一个。

  metadata {
    sshKeys = "${var.ssh_user}:${var.ssh_key} \n${var.ssh_user1}:${var.ssh_key1}"
}
Run Code Online (Sandbox Code Playgroud)


cou*_*elk 5

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

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

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

  # ...
}
Run Code Online (Sandbox Code Playgroud)

(请=metadata令牌和ssh-keysvs 后面注意符号sshKeys)。


has*_*ier 5

如果你想要多个密钥,你可以heredoc这样使用

  metadata = {
    "ssh-keys" = <<EOT
<user>:<key>
<user>:<key>
EOT
  }
Run Code Online (Sandbox Code Playgroud)

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