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

在Terraform中配置EC2密钥对报错:PublicKeyMaterial长度超限如何解决?

问题:Terraform创建EC2密钥对时提示PublicKeyMaterial长度超出限制?

我在Terraform中配置EC2实例密钥对时编写了如下main.tf代码:

terraform {
  required_providers {
    aws = {
      source  = "hashicorp/aws"
      version = "~> 4.16"
    }
  }

  required_version = ">= 1.2.0"
}

provider "aws" {
  region = "us-east-1"
}

variable "public_path" {
  default = "/path/to/MyKeyPair.pem"
}

resource "aws_key_pair" "app_keypair" {
  public_key = file(var.public_path)
  key_name   = "somekeyname"
}

resource "aws_instance" "app_server" {
  ami           = "ami-052efd3df9dad4825"
  instance_type = "t2.micro"

  vpc_security_group_ids = ["sg-xxxxx"]
  key_name               = aws_key_pair.app_keypair.key_name

  tags = {
    Name = "ExampleAppServerInstance"
  }
}

执行terraform apply时出现如下错误:

Plan: 2 to add, 0 to change, 0 to destroy.

Do you want to perform these actions?
  Terraform will perform the actions described above.
  Only 'yes' will be accepted to approve.

  Enter a value: yes

aws_key_pair.app_keypair: Creating...
╷
│ Error: error importing EC2 Key Pair (somekeyname): InvalidParameterValue: Value for parameter PublicKeyMaterial is invalid. Length exceeds maximum of 2048.
│       status code: 400, request id: 72425610-202e-42ce-98b4-a8dce5fef694
│
│   with aws_key_pair.app_keypair,
│   on main.tf line 21, in resource "aws_key_pair" "app_keypair":
│   21: resource "aws_key_pair" "app_keypair" {
│

错误原因

  • 你通过file()读取的是私钥文件(.pem),而非公钥文件。私钥包含加密的密钥数据,长度远超过AWS允许的2048字符上限,因此触发参数无效错误。
  • AWS EC2密钥对仅接受符合OpenSSH格式的公钥内容(通常文件后缀为.pub),私钥内容不符合要求。

解决方法

1. 使用正确的公钥文件

找到对应私钥的公钥文件(例如MyKeyPair.pub),修改variable "public_path"的默认值为该文件路径:

variable "public_path" {
  default = "/path/to/MyKeyPair.pub"
}

2. 从私钥生成公钥(如果没有公钥文件)

使用OpenSSH命令从现有私钥导出公钥:

ssh-keygen -y -f /path/to/MyKeyPair.pem > /path/to/MyKeyPair.pub

生成完成后,将配置中的public_path替换为这个新生成的.pub文件路径。

3. 验证公钥格式

确保公钥内容以ssh-rsa或ecdsa-sha2-nistp256等合法前缀开头,内容长度在AWS要求范围内(RSA公钥通常为1000-2000字符)。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.22 11:57:18