i am running a packer build and getting the image_id as a output from that command and now i need to automate the image_id coming from the packer as a input to the image_id of my terraform script so that i dont have to manually edit my terraform.tf file and paste the image_id.
There is no first-class integration between Packer and Terraform here because build tasks and provisioning/deployment tasks tend to be separated for most people, especially once they go into production and are running Packer and Terraform in automation.
With that said, the general goal here would be to arrange for your build process to somehow publish the id of the artifact it has produced somewhere that Terraform can find it. That requires some sort of data store that Packer (or a wrapper script around Packer) can write to and that Terraform can read from.
There are lots of different ways to glue those parts together depending on your detailed requirements, but here is one approach that I’ve used a variant of before:
- In your Packer template, use the
manifestpost-processor to get Packer to write out what it generated to a JSON file.
- Write a small custom program to read that Packer JSON file, extract the id(s) you are interested in, and publish them to something like AWS SSM Parameter Store, or any other suitable configuration/data store that Terraform has a data source to read from.
- In your Terraform configuration, use a data source to read whatever location your custom script wrote the result into and then pass the resulting id into whatever other parts of your configuration need it.
This approach decouples the build process from the provisioning/deploy process so that Packer doesn’t know anything about Terraform and Terraform doesn’t know anything about Packer: you could swap out either technology later without affecting the overall approach. By recording the current artifact in a particular location, you can also create workflows for rolling back to a previous artifact if you find that a new artifact is faulty in some way; you can write an old artifact id into the same location and run Terraform again to re-deploy with the old artifact.
If you are running Terraform in automation (which I’d recommend for production use) then it can be convenient to configure your automation system to automatically trigger the Terraform job whenever the Packer job completes successfully, but still keeping the Terraform job separate so that you can launch it directly when you need to run Terraform for any reason other than having built a new artifact.