A few months ago when I posted on building Packer images with Terraform I shared how I use the ID of the null resource to look up the image that I built. While this has worked out pretty well, I started having some trouble if the previous Terraform run failed.

I learned that Terraform’s null_resource will still create an ID and put it in the state file even if the null_resource fails, so that on the subsequent runs, the aws_ami data resource will try to look up an AMI with that ID, causing the Terraform to fail. This would happen even if the null resource was going to be built again. To fix it, I would have to comment out the tag:id filter and search only for the name, at least until I got the stack back into good shape.

Thankfully, it was a pretty easy fix. Since I rebuild my AMIs every time the Terraform runs, I just added a depends_on clause to the aws_ami data resource:

data "aws_ami" "this" {
  depends_on = [null_resource.packer]
  filter {
    name   = "tag:id"
    values = [null_resource.packer.id]
  }
  filter {
    name   = "name"
    values = [join("-", [var.name, "*"])]
  }

  most_recent = true
  owners      = ["self"]
}

Now when I run my terraform, it will wait for the packer image to build before getting the new ID and placing it in the search.