We have several options to discover an AMI id to use in infra as code resources, but with Packer from Hashicorp it is simple as define a block that will recover based on a pattern the id.
Above the solution using filter to restore latest image id for a ubuntu 20.04 version.