Warm tip: This article is reproduced from stackoverflow.com, please click
terraform provisioning terraform-cloud

How to send local files using Terraform Cloud as remote backend?

发布于 2020-04-10 10:19:10

I am creating AWS EC2 instance and I am using Terraform Cloud as backend.

in ./main.tf:

terraform {

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

  }

in ./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")}"
    }
  }
}

and as a result, I got the following error:

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

so what is happening here, is that terraform trying to find the file in Terraform Cloud instead of my local machine. How can I transfer file from my local machine and still using Terraform Cloud?

Questioner
Kingindanord
Viewed
80
Kingindanord 2020-03-25 10:20

There is no straight way to do what I asked in the question. In the end I ended up uploading the keys into AWS with its CLI like this:

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

and then reference it like that:

resource "aws_instance" "test" {

    ami = "${var.ami_id}"

    ...

    key_name      = "name_for_the_key"   

    ...

}

Note Yes file:// looks like the "Windowsest" syntax ever but you have to use it on linux too.