/ devops

Packer Recipes to bake an EC2 AMI

Debugging your template

So you read the introduction to Packer and started creating AMIs and then things are not working (which is expected).Packer immediately terminates machine before you think of what is wrong.Its during these difficult time one mist run Packer with -debug option.

Now Packer wait for you to hit the enter key before moving to next step, giving you ample time to debug the run instance which is used to create the image.
The ssh key for the machine will be stored in the location from where you issued the command (if you are using temporary key-pair).

 packer build -debug -var'SECRET=TOPSECRET' packer-template.json 


Debug mode enabled. Builds will not be parallelized.
amazon-ebs output will be in this color.

==> amazon-ebs: Prevalidating AMI Name: centos_7_nginx
==> amazon-ebs: Pausing after run of step 'StepPreValidate'. Press enter to continue.

All snippets are relevant to creating AMI and the builder used is amazon-ebs.

Encrypting Volumes

So you were all happy using Packer to build images when from no where came the info-sec folks with a very valid requirement to mandate volumes of new instances created from the AMI to be encrypted.Packer gives an option to encrypt boot volume.

"encrypt_boot": true

And if you don't want to use default key you can specify the KMS key id.

"kms_key_id": "{{user `kms_key_id`}}"

Use existing key-pairs

By default Packer creates a new key-pair for SSH each time we try to build an AMI.This is all good unless you are using an IAM User credentials to run Packer and this user doesn't have the permission to create/delete key-pairs (for what ever IT Governance reasons).
Packer lets you use an existing key-pair by specifying:

"ssh_keypair_name": "{{user `ssh_keypair_name`}}",

You should specify the name of the key-pair and location where the .pem file is present.

sudo: sorry, you must have a tty to run sudo

This happens because in your Linux Distributions /etc/sudoers file have Defaults requiretty set. This means all sudo commands executed require a tty teletype .

Packer ssh communicator provides an options ssh_pty which we can set to true. It will request for a pseudo terminal at server side during ssh.The defaults value for this option is false.

"builders": [
      "communicator": "ssh",
      "ssh_pty" : true

Clean up old Images | DANGER!!!

Everytime you create a new AMI if you want an old AMI with same name to be deregistered set force_deregister to true , by default it is false.

Every AMI also have a snapshot of the volume, if you want to delete that as well force_delete_snapshot

"force_deregister": true,
"force_delete_snapshot": true 

This will save some cost as well for s3 storage used by snapshots.


Packer Documentation