地形 v0.12.21 抛出"Failed to read ssh private key: no key found"



无法从terraform连接到ec2实例。如果我手动创建ec2实例(而不是通过terraform(,那么相同的密钥对也能工作。这证实了我的钥匙对是正确的。这是我正在尝试执行的代码。我得到的错误是:`aws_instance.ec2_test_instance:Provisioning with'remoteexec'。。。

错误:读取ssh私钥失败:找不到密钥

错误:错误导入KeyPair:MissingParameter:请求必须包含参数PublicKeyMaterial状态代码:400,请求id:`

resource "aws_instance" "ec2_test_instance" {
ami           = var.instance_test_ami
instance_type = var.instance_type
subnet_id     = var.aws_subnet_id
key_name      = aws_key_pair.deployer.key_name
tags = {
Name = var.environment_tag
}
connection {
type    = "ssh"
host    = self.public_ip
user    = "centos"
private_key   = "file(path.root/my-key)"
}
provisioner "remote-exec" {
inline = [
"sudo yum -y install wget, unzip",
"sudo yum -y install java-1.8.0-openjdk",
]
}

您需要在路径中使用${}作为插值语法:

private_key = file("${path.module}/my-key")

在文档中,示例在参数字段中的实际文件路径周围显示${}:https://www.terraform.io/docs/configuration/functions/file.html

terraform文件函数的文档帮助了我,来自同一个线程的这个答案帮助了我。

在我的案例中,我在为远程exec和文件函数设置连接块时收到了同样的错误,该函数复制了一个脚本,并在提供AWS实例后运行它。以下是资源块的示例片段:


resource "local_file" "my_script" {
content  = <<-EOT
#!/bin/bash

echo "Hello World"

EOT
filename = "${path.root}/my_script.sh"
}


resource "aws_instance" "aws_instance_name" {
ami                         = var.aws_instance_AMI
instance_type               = var.aws_instance_type
key_name                    = var.aws_key_variable_name
vpc_security_group_ids      = [aws_security_group.aws_instance_sg.id]
count                       = 3
subnet_id                   = var.subnet_variable                            
private_ip                  = var.list_private_ips_aws_instance[count.index]
associate_public_ip_address = true


provisioner "file" {
source      = local_file.my_script.filename
destination = "/tmp/my_script.sh" # Destination path on the instance
connection {
host        = self.public_ip # Use the public IP address of the instance
type        = "ssh"
user        = var.ansible_become_user
private_key = file("${var.aws_key_variable_name}.pem")
}
}

# Use the remote-exec provisioner to run the script
provisioner "remote-exec" {
inline = [
"chmod +x /tmp/my_script.sh",
"sudo /tmp/my_script.sh arg_1 arg_2"
]
connection {
host        = self.public_ip # Use the public IP address of the instance
type        = "ssh"
user        = var.ansible_become_user
private_key = file("${var.aws_key_variable_name}.pem")
}
}

相关内容

最新更新