Builders
We need to tell Packer what base server image we will use to build upon. We're not making a server image from scratch, instead we use our cloud providers base images and build on top of them.
We could simply tell Packer that directly via "source_ami":"ami-07c1207a9d40bc3bd"
, but we'll instead use a filter to find the latest AMI for our use case.
We'll use the (standard) Packer Builder amazon-ebs
. You can see all available builders here.
Here's how you make an AMI in AWS:
- Create a server with an EBS root drive
- EBS (Elastic Block Storage) are the disk drives in AWS
- Install and configure the server however you'd like
- Create a snapshot of the EBS root volume
- Convert that snapshot to an AMI
Here's what it looks like to have Packer choose AWS server to build upon. We'll ask Packer to use a filter (using the AWS API) to find the latest Ubuntu 20.04 AMI created by Canonical.
1{ 2 "min_packer_version":"1.0.0", 3 "variables":{
4 "infra_name": "cloudcasts", 5 "infra_env": "", 6 "aws_region": "us-east-2", 7 "aws_instance": "t3.small" 8 }, 9 "builders":[10 {11 "type":"amazon-ebs",12 "ami_name":"{{user `infra_name`}}-{{user `infra_env`}}-{{timestamp}}-app",13 "instance_type":"{{user `aws_instance`}}",14 "region":"{{user `aws_region`}}",15 "profile": "cloudcasts",16 17 "source_ami_filter": {18 "filters": {19 "architecture": "x86_64",20 "name": "ubuntu/images/hvm-ssd/ubuntu-focal-20.04-amd64-server-*",21 "root-device-type": "ebs",22 "virtualization-type": "hvm"23 },24 "most_recent": true,25 "owners": [26 "099720109477"27 ]28 },29 "ssh_username":"ubuntu",30 "launch_block_device_mappings":[31 {32 "device_name":"/dev/sda1",33 "volume_size": 8,34 "delete_on_termination": true,35 "encrypted":false,36 "volume_type": "gp3",37 "throughput": 125,38 "iops": 300039 }40 ],41 "tags":{42 "Name":"{{user `infra_name`}}-{{user `infra_env`}}-{{timestamp}}-app",43 "Project":"{{user `infra_name`}}",44 "Environment":"{{user `infra_env`}}",45 "Role":"baked-ami",46 "Unique":"baked-ami-{{timestamp}}",47 "ManagedBy":"packer",48 "Component":"app"49 }50 }51 ],52 "provisioners":[...]53}
We tell Packer how base image to use and how to create it (giving it an 8gb EBS drive, for example).
We also tell Packer to give the AMI we create some tags to be applied when it is created.
Tagging resources is super important in AWS to help search for resources, segment them (e.g. by environment), and for cost allocation and reporting.