Packer for building AMI on EC2 and beyond.

Using Hashicorp’s packer to build AMI on EC2 is a breeze. This tool can be used also with other platform to build images. In this example, Ansible provisioner is used to setup the instance before packer finalize the EC2 instance to be built as image.

This will build a simple Ubuntu Trusty Amazon Linux Image(AMI) with Nginx installed.
The idea is to get it to work before doing a complex playbook.

In order to run packer’s Ansible provisioner, Ansible must properly be setup.
See docs on how to setup Ansible here.

Requirements for this setup.
* Ansible installed
* Packer installed

 
$ ansible --version  | head -n1
ansible 2.1.2.0 (stable-2.1 3808a00118) last updated 2016/09/13 15:17:18 (GMT +800)

Now define the needed Environment variables for your Packer and AWS.

$ export PATH=$PATH:~/packer
$ export AWS_ACCESS_KEY_ID=YOUR_ACCESS_KEY_HERE
$ export AWS_SECRET_ACCESS_KEY=YOUR_SECRET_KEY_HERE
$ export AWS_DEFAULT_REGION=us-east-1
$ packer --version
0.10.1

The codes are here:
https://github.com/cocoy/packer-sample

$ git clone https://github.com/cocoy/packer-sample.git
$ cd packer-sample

Checking the packer_ansible.json

$ cat packer_ansible.json
{
  "builders": [{
   "type": "amazon-ebs",
   "region": "us-east-1",
   "source_ami": "ami-e902508c",
   "instance_type": "t1.micro",
   "ssh_username": "ubuntu",
   "ami_name": "Ubuntu 14.04 Packer - {{timestamp}}"
  }],

  "provisioners": [{
   "type": "ansible",
   "playbook_file": "./playbook.yml"
  }]
}

And the simple playbook:

$ cat playbook.yml
---
- hosts: all
remote_user: ubuntu
become: yes
become_method: sudo

# More roles can be added here too.
#roles:
# - { role: pcextreme.nginx }
#
pre_tasks:
- name: update apt
apt: update_cache=yes

- name: install add_apt command
apt: name=python-software-properties state=installed

- name: install nginx
apt: name=nginx

Then start building the AMI.

$ packer build packer_ansible.json

Watch how it is being launch, provisioned, and build the AMI!

Leave a Reply

Your email address will not be published. Required fields are marked *