Terraform Resource: Connection Error while executing apply?

痞子三分冷 提交于 2021-02-10 12:49:44

问题


I am trying to login to ec2 instance that terraform will create with the following code:

resource "aws_instance" "sess1" {
  ami           = "ami-c58c1dd3"
  instance_type = "t2.micro"
  key_name        = "logon"

      connection {
        host= self.public_ip
        user        = "ec2-user"
        private_key = file("/logon.pem")
     }
    
      provisioner "remote-exec" {
        inline = [
          "sudo yum install nginx -y",
          "sudo service nginx start"
        ]
      }
    }

But this gives me an error:

PS C:\Users\Amritvir Singh\Documents\GitHub\AWS-Scribble\Terraform> terraform apply
provider.aws.region
  The region where AWS operations will take place. Examples
  are us-east-1, us-west-2, etc.

  Enter a value: us-east-1


Error: Invalid function argument

  on Session1.tf line 13, in resource "aws_instance" "sess1":
  13:     private_key = file("/logon.pem")

Invalid value for "path" parameter: no file exists at logon.pem; this function
works only with files that are distributed as part of the configuration source
code, so if this file will be created by a resource in this configuration you
must instead obtain this result from an attribute of that resource.

How do I save pass the key from resource to provisioner at runtime without logging into the console?


回答1:


connection should be in the provisioner block:

resource "aws_instance" "sess1" {
    
  ami           = "ami-c58c1dd3"
  instance_type = "t2.micro"
  key_name      = "logon"

 
  provisioner "remote-exec" {

    connection {
        host= self.public_ip
        user        = "ec2-user"
        private_key = file("/logon.pem")
     }

    inline = [
      "sudo yum install nginx -y",
      "sudo service nginx start"
    ]
  }
}

The above assumes that everything else is correct, e.g. the key file exist or security groups allow for ssh connection.




回答2:


Have you tried using the full path? Especially beneficial if you are using modules. I.E:

private_key = file("${path.module}/logon.pem")

Or I think even this will work

private_key = file("./logon.pem")

I believe your existing code is looking for the file at the root of your filesystem.



来源:https://stackoverflow.com/questions/63613944/terraform-resource-connection-error-while-executing-apply

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!