在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
相关产品推荐
相关产品推荐

