Introduction

In the world of cloud computing and infrastructure as code, Terraform stands out as a popular tool for automating the deployment of resources in cloud environments like AWS. However, even experienced developers can encounter errors. A common issue is the InvalidAMIID.Malformed error, which can be a stumbling block for many. This article aims to dissect and provide solutions to this error, drawing from a real-world example.

The Problem

While I was going through a Terraform tutorial, I encountered an error when trying to launch a source instance in AWS. The error message was:

Error: Error launching source instance: InvalidAMIID.NotFound: The image id '[ami-830c94e3]' does not exist
status code: 400, request id: 4c3e0252-c3a5-471e-8b57-3f6e349628af

This error occurred after changing the AWS region from us-west-2 to eu-central-1 in his Terraform configuration.

provider "aws" {
  region  = "eu-central-1"
}

The Cause

AMI IDs (Amazon Machine Images) are unique to each AWS region. When you change regions in your Terraform configuration, you also need to use an AMI that is available in that new region. The error occurred because the AMI ID used (ami-830c94e3) was not valid for the eu-central-1 region.

The Solution

Manual AMI ID Update

The immediate solution, as discovered by Lukasz Dynowski, is to manually find and specify the correct AMI ID for the intended region. This involves:

  1. Going to the AWS EC2 console.
  2. Selecting the desired region.
  3. Navigating to ‘Launch Instance’.
  4. Finding the correct AMI ID for the desired image in the new region.

For example, ami-07dfba995513840b5 might be the ID for Red Hat Enterprise Linux 8 in the eu-central-1 region.

Automated AMI Selection

A more robust solution is to use Terraform’s aws_ami data source, which allows for the dynamic selection of AMI IDs based on specified criteria. This approach automatically selects the correct AMI ID for the configured region and can update the AMI ID when newer images are available.

Here’s an example of how to use the aws_ami data source for an Ubuntu 20.04 AMI:

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" "web" {
  ami           = data.aws_ami.ubuntu.id
  instance_type = "t3.micro"

  tags = {
    Name = "Development"
  }
}

Conclusion

The InvalidAMIID.Malformed error in Terraform typically arises from using an AMI ID not valid for the specified AWS region. The solution involves either manually updating the AMI ID to match the region or employing a dynamic AMI selection approach using the aws_ami data source. This not only resolves the issue but also enhances the automation and flexibility of Terraform configurations.