You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用Terraform创建EC2实例部署HTTP服务器报错Invalid function argument

Terraform 部署EC2读取私钥文件报错解决方案

错误说明

报错原文:

on main.tf line 54, in resource "aws_instance" "http_server":
 54:     private_key = file(var.aws_key_pair)
 ├────────────────
 │ var.aws_key_pair 为 "~\aws\aws_keys"
Invalid value for "path" parameter: no file exists at ~\aws\aws_keys; 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.

该报错核心原因是file()函数无法定位到指定路径下的私钥文件,按对应场景解决即可:

场景1:私钥文件已提前生成存在本地

  • 替换波浪号别名路径:Terraform的file()函数不支持Windows系统下的~用户目录别名,需替换为完整绝对路径,比如C:\Users\你的用户名\aws\aws_keys;跨平台使用建议将私钥文件放到Terraform配置同级目录下,使用相对路径./aws_keys访问。
  • 检查文件有效性:确认路径拼写正确,没有隐藏的文件后缀(比如实际文件是aws_keys.pem但路径漏写了后缀),Linux/macOS系统需确保运行Terraform的用户对私钥文件有读权限,建议设置权限为600避免后续SSH连接报错。
  • 优化路径写法:可以用Terraform内置的path.module变量拼接路径,保证不同运行环境都能正确定位到配置目录下的文件,示例:private_key = file("${path.module}/aws_keys")

场景2:私钥由当前Terraform配置内的aws_key_pair资源生成

这种情况不要用file()函数读取还未生成的本地文件,直接引用资源的输出属性即可。
假设你的密钥对资源定义如下:

resource "aws_key_pair" "http_server_key" {
  key_name   = "http_server_key"
  public_key = tls_private_key.rsa.public_key_openssh
}

直接修改aws_instance中的配置为:
private_key = aws_key_pair.http_server_key.private_key
即可直接获取资源生成的私钥内容,无需读取本地文件。

内容的提问来源于stack exchange,提问作者Laxmi Tulasi

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.01 07:42:02