2

我正在创建 AWS EC2 实例,并且使用 Terraform Cloud 作为后端。

./main.tf中:

terraform {

    required_version = "~> 0.12"
    backend "remote" {
    hostname     = "app.terraform.io"
    organization = "organization"
    workspaces { prefix = "test-dev-" }

  }

./modules/instances/function.tf


resource "aws_instance" "test" {
    ami = "${var.ami_id}"
    instance_type = "${var.instance_type}"
    subnet_id = "${var.private_subnet_id}"
    vpc_security_group_ids = ["${aws_security_group.test_sg.id}"]
    key_name      = "${var.test_key}"                                        

    tags = {
        Name = "name"
        Function = "function"
    }

  provisioner "remote-exec" {
    inline = [
      "sudo useradd someuser"
    ]

    connection {
      host = "${self.public_ip}"
      type        = "ssh"
      user        = "ubuntu"
      private_key = "${file("~/.ssh/mykey.pem")}"
    }
  }
}

结果,我收到以下错误:

Call to function "file" failed: no file exists at /home/terraform/.ssh/...

所以这里发生的事情是,terraform 试图在 Terraform Cloud 而不是我的本地机器中查找文件。如何从本地计算机传输文件并仍在使用 Terraform Cloud?

4

1 回答 1

3

没有直接的方法可以做我在问题中提出的问题。最后,我最终使用它的 CLI 将密钥上传到 AWS,如下所示:

aws ec2 import-key-pair --key-name "name_for_the_key" --public-key-material file:///home/user/.ssh/name_for_the_key.pub

然后像这样引用它:

resource "aws_instance" "test" {

    ami = "${var.ami_id}"

    ...

    key_name      = "name_for_the_key"   

    ...

}

注意Yesfile://看起来像“Windowsest”语法,但你也必须在 linux 上使用它。

于 2020-03-25T02:20:07.053 回答