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

How to add an ssh key to an GCP instance using 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

我认为这样的事情应该可行:

  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

这里是测试过的。

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

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

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

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

  # ...
}

(注意 =metadata 标记后签名,ssh-keyssshKeys 对比)。

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

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

我在 terraform fmt 提供给我的 post 中使用了奇怪的格式。

您可以使用以下

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

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

只是更新 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"
      }
  ]
}

下面为我工作:对于所有虚拟机,一个 ssh 密钥

resource "google_compute_project_metadata" "my_ssh_key" {
  metadata = {
    ssh-keys = <<EOF
      terakey:ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAICqaF7TqtimTUtqLdZIspKjuTXXXXnkbW7N9TQBPXazu terakey
      
    EOF
  }
}