How to Get the AMI id after a Packer build

Packer has a functionality called postprocessor. This creates a manifest JSON file which contains all the information about the packer build including the AMI id. Fromm which you can read the AMI id. You can add the post processor in you packer template like shown below.

"post-processors": [
  "type": "manifest",
  "output": "manifest.json",
  "strip_path": true

There is no direct way of getting just the AMI id from a packer build process. However, there are few workarounds that will get you the final AMI id.

####Get the id from output file

You can write the build output to an output file and get the id from that file. You can use the following script for that.

packer build app.json 2>&1 | sudo tee output.txt
tail -2 output.txt | head -2 | awk 'match($0, /ami-.*/) { print substr($0, RSTART, RLENGTH) }' > sudo ami.txt

####Run packer build with -machine-readable flag

Use the machine-readable flag and parse the id from the console output. An example is shown below.

packer build -machine-readable packer.json | tee build.log
grep 'artifact,0,id' build.log | cut -d, -f6 | cut -d: -f2

####Get the ami id in the console.

To get the AMI id in the console, you could use the following.

packer build -machine-readable packer.json | awk -F, '$0 ~/artifact,0,id/ {print $6}'