【问题标题】:Terraform: can't remote-exec on a compute engine VM with generated SSH keyTerraform:无法使用生成的 SSH 密钥在计算引擎 VM 上远程执行
【发布时间】:2019-09-01 00:43:07
【问题描述】:

我正在尝试使用带有 Terraform 的 ssh 密钥在新配置的 Google Cloud Platform Compute Engine VM 上远程执行一些命令。这是我的代码:

resource "tls_private_key" "ssh-key" {
  algorithm = "RSA"
  rsa_bits  = 4096
}

resource "google_compute_instance" "static-content" {

  # ...

  metadata {
    sshKeys = "root:${tls_private_key.ssh-key.public_key_openssh}"
  }

  connection {
    type = "ssh"
    user = "root"
    private_key = "${tls_private_key.ssh-key.private_key_pem}"
  }

  provisioner "remote-exec" {
    inline = [
      "curl -L https://github.com/aelsabbahy/goss/releases/download/v0.3.6/goss-linux-amd64 -o ~/goss",
      "chmod +x ~/goss",
      "~/goss -g ~/gossfile.yml validate",
    ]
  }

}

我在 Terraform 应用中得到的输出是

google_compute_instance.static-content: Still creating... (2m10s elapsed)
google_compute_instance.static-content (remote-exec): Connecting to remote host via SSH...
google_compute_instance.static-content (remote-exec):   Host: 35.198.166.131
google_compute_instance.static-content (remote-exec):   User: root
google_compute_instance.static-content (remote-exec):   Password: false
google_compute_instance.static-content (remote-exec):   Private key: true
google_compute_instance.static-content (remote-exec):   SSH Agent: false
google_compute_instance.static-content (remote-exec):   Checking Host Key: false

所以 ssh 密钥似乎没有正确传播到 VM。任何提示为什么这不起作用?

【问题讨论】:

    标签: google-cloud-platform terraform ssh-keys terraform-provider-gcp


    【解决方案1】:

    您似乎只是以不同的方式尝试了它,试试下面对我有用的代码

    provisioner "remote-exec" {
    connection {
    type = "ssh"
    port = 22
    user = "username"
    agent = "false"
    private_key = "${file("/path/to/your/pem_file")}"
    }
     inline = [
     "your command goes here",
      ]
    }
    }
    

    【讨论】:

    • 这是一个生成的 SSH 密钥(如 stackoverflow.com/a/49792833/2291321),而不是位于用户文件系统上的密钥。
    • 我以前试过这种方法,也没有用。似乎问题是试图以 root 的身份 ssh 进入机器,这似乎是不允许的。当我更改为gcp 用户并使用sudo 运行命令时,一切正常。还是谢谢你!
    猜你喜欢
    • 2020-12-04
    • 1970-01-01
    • 1970-01-01
    • 2019-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-06-12
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多