I had a similar error when trying to create an Ubuntu 20.04 AWS EC2 instance using Terraform.
I was running into this error when I run the terraform apply command:
Error: Error launching source instance: InvalidAMIID.Malformed: Invalid id: "data.aws_ami.ubuntu.id" (expecting "ami-...")
status code: 400, request id: 9cb0ddbc-1f5e-43e7-bef2-541832aa002e
My code looks like this:
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"
}
}
Here's how I fixed it:
The issue was that I put data.aws_ami.ubuntu.id in quotes which is a call/invocation operation of the data function::
resource "aws_instance" "ec2" {
ami = "data.aws_ami.ubuntu.id"
instance_type = "t2.micro"
I had to remove the quotes from data.aws_ami.ubuntu.id:
resource "aws_instance" "web" {
ami = data.aws_ami.ubuntu.id
instance_type = "t2.micro"
So my code looked like this afterwards:
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"
}
}
This time when I ran terraform apply command,it printed the correct ami id for the ubuntu 20.04 aws ec2 instance in my specified region:
data.aws_ami.ubuntu: Refreshing state... [id=ami-0885b1f6bd170450c]
and then created the aws instance resource.
Note: The specified name for the resource which is ec2 can be of any value of your choice. You can name it web or whatever name you desire:
resource "aws_instance" "web" {
ami = data.aws_ami.ubuntu.id
instance_type = "t2.micro"
That's all.
I hope this helps