【问题标题】:Terraform Resource: Connection Error while executing apply?Terraform 资源:执行应用时出现连接错误?
【发布时间】:2020-12-16 05:12:02
【问题描述】:

我正在尝试登录到 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"
        ]
      }
    }

但这给了我一个错误:

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.

如何在不登录控制台的情况下在运行时将密钥从资源传递到配置程序?

【问题讨论】:

    标签: amazon-web-services terraform terraform-provider-aws


    【解决方案1】:

    您是否尝试过使用完整路径?如果您使用模块,则特别有用。 即:

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

    或者我认为即使这样也行

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

    我相信您现有的代码正在文件系统的根目录中查找该文件。

    【讨论】:

    • 添加 ${path.module} 有帮助。谢谢!
    【解决方案2】:

    connection 应该在 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"
        ]
      }
    }
    

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

    【讨论】:

    • @Amritvirsinghx 没问题。如果答案有帮助,我们将不胜感激。
    猜你喜欢
    • 2022-01-27
    • 2021-08-31
    • 1970-01-01
    • 2021-08-11
    • 2020-09-18
    • 2021-02-28
    • 1970-01-01
    • 1970-01-01
    • 2013-06-05
    相关资源
    最近更新 更多