Terraform 资源:执行应用时出现连接错误?

Amr*_*ghx 5 amazon-web-services terraform terraform-provider-aws

我正在尝试登录 terraform 将使用以下代码创建的 ec2 实例:

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"
        ]
      }
    }
Run Code Online (Sandbox Code Playgroud)

但这给了我一个错误:

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.
Run Code Online (Sandbox Code Playgroud)

如何在运行时保存从资源到配置程序的密钥传递而不登录控制台?

Mar*_*cin 0

连接应该在provisioner块中:

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"
    ]
  }
}
Run Code Online (Sandbox Code Playgroud)

上面假设其他一切都正确,例如密钥文件存在或安全组允许 ssh 连接。