我在尝试使用 Terraform 创建 Ubuntu 20.04 AWS EC2 实例时遇到了类似的错误。
我在运行terraform apply 命令时遇到了这个错误:
错误:启动源实例时出错:InvalidAMIID.Malformed:无效 id:“data.aws_ami.ubuntu.id”(预期为“ami-...”)
状态码:400,请求ID:9cb0ddbc-1f5e-43e7-bef2-541832aa002e
我的代码如下所示:
provider "aws" {
region = "us-east-1"
}
data "aws_ami" "ubuntu" {
most_recent = true
filter {
name = "name"
values = ["ubuntu/images/hvm-ssd/ubuntu-focal-20.04-amd64-server-*"]
}
filter {
name = "virtualization-type"
values = ["hvm"]
}
owners = ["099720109477"] # Canonical
}
resource "aws_instance" "ec2" {
ami = "data.aws_ami.ubuntu.id"
instance_type = "t2.micro"
tags = {
Name = "HelloWorld"
}
}
这是我修复它的方法:
问题是我将data.aws_ami.ubuntu.id 放在引号中,这是data 函数的调用/调用操作::
resource "aws_instance" "ec2" {
ami = "data.aws_ami.ubuntu.id"
instance_type = "t2.micro"
我不得不从data.aws_ami.ubuntu.id 中删除引号:
resource "aws_instance" "web" {
ami = data.aws_ami.ubuntu.id
instance_type = "t2.micro"
所以我的代码后来看起来像这样:
provider "aws" {
region = "us-east-1"
}
data "aws_ami" "ubuntu" {
most_recent = true
filter {
name = "name"
values = ["ubuntu/images/hvm-ssd/ubuntu-focal-20.04-amd64-server-*"]
}
filter {
name = "virtualization-type"
values = ["hvm"]
}
owners = ["099720109477"] # Canonical
}
resource "aws_instance" "ec2" {
ami = data.aws_ami.ubuntu.id
instance_type = "t2.micro"
tags = {
Name = "HelloWorld"
}
}
这一次我运行terraform apply 命令时,它为我指定区域中的 ubuntu 20.04 aws ec2 实例打印了正确的 ami id:
data.aws_ami.ubuntu: Refreshing state... [id=ami-0885b1f6bd170450c]
然后创建 aws 实例资源。
注意:resource 的指定名称ec2 可以是您选择的任何值。您可以将其命名为 web 或任何您想要的名称:
resource "aws_instance" "web" {
ami = data.aws_ami.ubuntu.id
instance_type = "t2.micro"
就是这样。
我希望这会有所帮助