Building EBS Boot AMIs Using Canonical's Downloadable EC2 Images

| 18 Comments

In the last article, I described how to use the vmbuilder software to build an EBS boot AMI from scratch for running Ubuntu on EC2 with a persistent root disk.

In the ec2ubuntu Google group, Scott Moser pointed out that users can take advantage of the Ubuntu images for EC2 that Canonical has already built with vmbuilder. This can simplify and speed up the process of building EBS boot AMIs for the rest of us.

Let’s walk through the steps, creating an EBS boot AMI for Ubuntu 9.10 Karmic.

  1. Run an instance of the Ubuntu 9.10 Karmic AMI, either 32-bit or 64-bit depending on which architecture AMI you wish to build. Make a note of the resulting instance id:

    # 32-bit
    instanceid=$(ec2-run-instances     --key YOURKEYPAIR                --availability-zone us-east-1a   ami-1515f67c |
      egrep ^INSTANCE | cut -f2)
    echo "instanceid=$instanceid"
    
    
    # 64-bit
    instanceid=$(ec2-run-instances     --key YOURKEYPAIR                --availability-zone us-east-1a   --instance-type m1.large         ami-ab15f6c2 |
      egrep ^INSTANCE | cut -f2)
    echo "instanceid=$instanceid"
    

    Wait for the instance to move to the “running” state, then note the public hostname:

    while host=$(ec2-describe-instances "$instanceid" | 
      egrep ^INSTANCE | cut -f4) && test -z $host; do echo -n .; sleep 1; done
    echo host=$host
    

    Copy your X.509 certificate and private key to the instance. Use the correct locations for your credential files:

    rsync                              --rsh="ssh -i YOURKEYPAIR.pem"   --rsync-path="sudo rsync"        ~/.ec2/{cert,pk}-*.pem           ubuntu@$host:/mnt/
    

    Connect to the instance:

    ssh -i YOURKEYPAIR.pem ubuntu@$host
    
  2. Install EC2 API tools from the Ubuntu on EC2 ec2-tools PPA because they are more up to date than the ones in Karmic, letting us register EBS boot AMIs:

    export DEBIAN_FRONTEND=noninteractive
    echo "deb http://ppa.launchpad.net/ubuntu-on-ec2/ec2-tools/ubuntu karmic main" |
      sudo tee /etc/apt/sources.list.d/ubuntu-on-ec2-ec2-tools.list &&
    sudo apt-key adv --keyserver keyserver.ubuntu.com --recv-keys 9EE6D873 &&
    sudo apt-get update &&
    sudo -E apt-get dist-upgrade -y &&
    sudo -E apt-get install -y ec2-api-tools
    
  3. Set up some parameters:

    codename=karmic
    release=9.10
    tag=server
    if [ $(uname -m) = 'x86_64' ]; then
      arch=x86_64
      arch2=amd64
      ebsopts="--kernel=aki-fd15f694 --ramdisk=ari-c515f6ac"
      ebsopts="$ebsopts --block-device-mapping /dev/sdb=ephemeral0"
    else
      arch=i386
      arch2=i386
      ebsopts="--kernel=aki-5f15f636 --ramdisk=ari-0915f660"
      ebsopts="$ebsopts --block-device-mapping /dev/sda2=ephemeral0"
    fi
    
  4. Download and unpack the latest released Ubuntu server image file. This contains the output of vmbuilder as run by Canonical.

    imagesource=http://uec-images.ubuntu.com/releases/$codename/release/unpacked/ubuntu-$release-$tag-uec-$arch2.img.tar.gz
    image=/mnt/$codename-$tag-uec-$arch2.img
    imagedir=/mnt/$codename-uec-$arch2
    wget -O- $imagesource |
      sudo tar xzf - -C /mnt
    sudo mkdir -p $imagedir
    sudo mount -o loop $image $imagedir
    
  5. [OPTIONAL] At this point /mnt/$image contains a mounted filesystem with the complete Ubuntu image as released by Canonical. You can skip this step if you just want an EBS boot AMI which is an exact copy of the released S3 based Ubuntu AMI from Canonical, or you can make any updates, installations, and customizations you’d like to have in your resulting AMI.

    In this example, we’ll perform similar steps as the previous tutorial and update the software packages to the latest releases from Ubuntu. Remember that the released EC2 image could be months old.

    # Allow network access from chroot environment
    sudo cp /etc/resolv.conf $imagedir/etc/
    # Fix what I consider to be a bug in vmbuilder
    sudo rm -f $imagedir/etc/hostname
    # Add multiverse
    sudo perl -pi -e 's%(universe)$%$1 multiverse%'   $imagedir/etc/ec2-init/templates/sources.list.tmpl
    # Add Alestic PPA for runurl package (handy in user-data scripts)
    echo "deb http://ppa.launchpad.net/alestic/ppa/ubuntu karmic main" |
      sudo tee $imagedir/etc/apt/sources.list.d/alestic-ppa.list
    sudo chroot $imagedir   apt-key adv --keyserver keyserver.ubuntu.com --recv-keys BE09C571
    # Add ubuntu-on-ec2/ec2-tools PPA for updated ec2-ami-tools
    echo "deb http://ppa.launchpad.net/ubuntu-on-ec2/ec2-tools/ubuntu karmic main" |
      sudo tee $imagedir/etc/apt/sources.list.d/ubuntu-on-ec2-ec2-tools.list
    sudo chroot $imagedir   apt-key adv --keyserver keyserver.ubuntu.com --recv-keys 9EE6D873
    # Upgrade the system and install packages
    sudo chroot $imagedir mount -t proc none /proc
    sudo chroot $imagedir mount -t devpts none /dev/pts
    cat <<EOF > $imagedir/usr/sbin/policy-rc.d
    #!/bin/sh
    exit 101
    EOF
    chmod 755 $imagedir/usr/sbin/policy-rc.d
    DEBIAN_FRONTEND=noninteractive
    sudo chroot $imagedir apt-get update &&
    sudo -E chroot $imagedir apt-get dist-upgrade -y &&
    sudo -E chroot $imagedir apt-get install -y runurl ec2-ami-tools
    sudo chroot $imagedir umount /proc
    sudo chroot $imagedir umount /dev/pts
    rm -f $imagedir/usr/sbin/policy-rc.d
    

    Again, the above step is completely optional and can be skipped to create the EBS boot AMI that Canonical would have published.

  6. Copy the image files to a new EBS volume, snapshot it, and register the snapshot as an EBS boot AMI. Make a note of the resulting AMI id:

    size=15 # root disk in GB
    now=$(date +%Y%m%d-%H%M)
    prefix=ubuntu-$release-$codename-$tag-$arch-$now
    description="Ubuntu $release $codename $tag $arch $now"
    export EC2_CERT=$(echo /mnt/cert-*.pem)
    export EC2_PRIVATE_KEY=$(echo /mnt/pk-*.pem)
    volumeid=$(ec2-create-volume --size $size --availability-zone us-east-1a |
      cut -f2)
    instanceid=$(wget -qO- http://instance-data/latest/meta-data/instance-id)
    ec2-attach-volume --device /dev/sdi --instance "$instanceid" "$volumeid"
    while [ ! -e /dev/sdi ]; do echo -n .; sleep 1; done
    sudo mkfs.ext3 -F /dev/sdi
    ebsimage=$imagedir-ebs
    sudo mkdir $ebsimage
    sudo mount /dev/sdi $ebsimage
    sudo tar -cSf - -C $imagedir . | sudo tar xvf - -C $ebsimage
    sudo umount $ebsimage
    ec2-detach-volume "$volumeid"
    snapshotid=$(ec2-create-snapshot "$volumeid" | cut -f2)
    ec2-delete-volume "$volumeid"
    while ec2-describe-snapshots "$snapshotid" | grep -q pending
      do echo -n .; sleep 1; done
    ec2-register                     --architecture $arch           --name "$prefix"               --description "$description"   $ebsopts                       --snapshot "$snapshotid"
    
  7. Depending on what you want to keep from the above process, there are various things that you might want to clean up.

    If you no longer want to use an EBS boot AMI:

    ec2-deregister $amiid
    ec2-delete-snapshot $snapshotid
    

    When you’re done with the original instance:

    ec2-terminate-instance $instanceid
    

In this example, I set /mnt to the first ephemeral store on the instance even on EBS boot AMIs. This more closely matches the default on the S3 based AMIs, but means that /mnt will not be persistent across a stop/start of an EBS boot instance. If Canonical starts publishing EBS boot AMIs, they may or may not choose to make the same choice.

Community feedback, bug reports, and enhancements for these instructions are welcomed.

[Update 2009-01-14: Wrapped upgrade/installs inside of /usr/sbin/policy-rc.d setting to avoid starting daemons in chroot environment.]

[Update 2010-01-22: New location for downloadable Ubuntu images.]

[Update 2010-03-26: Path tweak, thanks to paul.]

18 Comments

Cool. Thanks!

BTW, have you or anyone else had an issue with EBS images and user data? Specifically, booting an EBS image, stopping it, changing the user data attribute (i.e., ec2-modify-instance-attribute --user-data), and the new user data not showing up when you restart the instance (i.e., it still shows the old user data)? IOW:

ec2-run-instances ami-xxxx -d ABC123
ec2-stop-instances i-xxxx
ec2-modify-instance-attribute --user-data XYZ987 i-xxxx
ec2-describe-instance-attribute i-xxxx --user-data
(shows the NEW user data)
ec2-start-instances i-xxxx
ssh root@xxxxx
wget -qO- http://169.254.169.254/latest/user-data
(shows the OLD user data)

Thanks for the tutorial! It hardly took any time at all to go through!

Using the "ubuntu" user was new to me. I thought I had copied my PK and CERT to /mnt, but actually I didn't have permission to write there and it failed.

But I didn't see that and kept going with the tutorial - it fails at step 6 because it waits for a snapshot that will never happen :). Actually I think I had to change the permissions on the keys after copying then there as root so that they could be properly read from the ubuntu user.

n.sherlock: In the above example, the "sudo rsync" gives the ubuntu user permission to write to /mnt so it will not fail.
No permissions need to be changed either. These commands can be copied and pasted with only a few changes to indicate your credential files sources.

Steve: This user-data behavior was reported on the EC2 forum and AWS offered to investigate: http://developer.amazonwebservices.com/connect/thread.jspa?messageID=160644

Whoops, you're quite right, Eric. I must have totally skipped over that section, since I "knew" how to copy a file in.. :).

I'm really loving my new Ubuntu EBS server. I have already shut it down several times. I love that I don't have to have a lengthy downtime just to take an image of it.

I'm also now switching to using the excellent ec2-consistent-snapshot for my database backups instead of mysqldump. mysqldump is too slow, it takes up to an hour to complete a backup on my server, making the site unavailable during that time by locking myisam tables. ec2-consistent-snapshot will be superb for backing up the database EBS RAID.

Eric: Thanks. That person (nomoneydown) is actually me. :) I sent Marc@AWS a PM per his request, but haven't gotten a response yet, so thought I'd ask around to see if anyone else is having the same problem (and it's not just something I'm doing/not doing). Also, sorry to "hijack" your thread about it, but didn't have a direct way of notifying you. :( But a sincere thanks to all your posts here as they are extremely helpful as are your AMI's, which I use routinely!

While making "apt-get dist-upgrade" in chroot, it ends with an error:

Setting up rsyslog (4.2.0-2ubuntu5.1) ...
start: Unable to connect to Upstart: Failed to connect to socket
/com/ubuntu/upstart: Connection refused
invoke-rc.d: initscript rsyslog, action "restart" failed.
dpkg: error processing rsyslog (--configure):
subprocess
installed post-installation script returned error
exit status 1
Errors were encountered while processing:
rsyslog
Is it just me or does anyone else also get that error?

maanus: I just updated the commands above to wrap the upgrade/installs inside of /usr/sbin/policy-rc.d setting to prevent the attempted restart of daemons in the chroot environment. Can you test and see if this helps?

Thank you! Now it is working correctly.
Also I had to use

export DEBIAN_FRONTEND=noninteractive
otherwise the "noninteractive" seemed to have no effect in chroot enviroment.
Just a note to newbie hackers who want to run these commands one by one: && is only useful if you paste several commands into your shell.

When I follow the commands above, I get the following error in step 5 (installing ec2-ami-tools into the chroot):

$ sudo -E chroot $imagedir apt-get install -y ec2-ami-tools
Reading package lists... Done
Building dependency tree       
Reading state information... Done
Some packages could not be installed. This may mean that you have
requested an impossible situation or if you are using the unstable
distribution that some required packages have not yet been created
or been moved out of Incoming.
The following information may help to resolve the situation:

The following packages have unmet dependencies:
ec2-ami-tools:
Depends: ruby but it is not installable
Depends: libopenssl-ruby but it is not installable

(What a nice name I have!)

If you're trying to use the EU region, you need to ensure you add

--region eu-west-1
to every ec2-something command.

When it gets to the last command, you have to use a kernel and ramdisk that are in your region. I used the IDs from my running instance* and it seems to have run OK.

Craig

* --kernel=aki-b02a01c4 --ramdisk=ari-39c2e94d

Just wanted to say thanks for such a great walkthrough! Just what I wanted, and I've learned a great deal along the way.

Rich.

Eric, nice instructions. I learned a lot. I'm a novice with EC2 and linux and just getting into EBS bootable AMIs.

I did find one error. The image name has likely changed since the instructions were written.

In step 4, I needed to add '$tag' with the appropriate '-' to the image variable assignment, because the image download contains 'server' in the name string.

Otherwise the subsequent mount command gives a 'no such file or directory' error, or similar.

change this line

image=/mnt/$codename-uec-$arch2.img

to this line

image=/mnt/$codename-$tag-luec-$arch2.img

Paul

Thanks Paul, I've fixed the path.

Hi Eric, this tutorial is really great. Is there a similar one for Lucid that would have all the right Lucid AMI id's?

@neil i had the same problem as

The following packages have unmet dependencies:

ec2-ami-tools:

Depends: ruby but it is not installable

Depends: libopenssl-ruby but it is not installable

add


deb http://us.archive.ubuntu.com/ubuntu/ lucid main restricted
deb-src http://us.archive.ubuntu.com/ubuntu/ lucid main restricted


to the end of /etc/apt/sources.list and execute

apt-get update && apt-get install -y ec2-ami-tools

First, thanks for all your interesting postings, but is there any change for current ubuntu releases? I don't find any more recent tutorial.

I'm currently failing to get this working for a oneiric host bundling a new instance also oneiric.

1. I had to download the ubuntu image from http://uec-images.ubuntu.com/releases/$codename/release/ubuntu-$release-$tag-cloud-img-$arch2.img.tar.gz rather than
http://uec-images.ubuntu.com/releases/$codename/release/unpacked/ubuntu-$release-$tag-uec-$arch2.img.tar.gz
Don't know if it makes any difference
2. when I got my new EBS volume ready, at first I had to change grub/menu.lst because of the default volume name. And finally this again did not boot, because the console reports missing modules.

Could you please point me to the right direction?
I tried vmbuilder on oneiric and did also not succeed because of missing --ec2 option.
My last thought would be to use the official ubuntu AMI's snapsho id as base for a new EBS drive and modify that, but I realized the snapshots itself are not public.
I tried for last two weeks now, and I am not any further.

Thanks!!!

Here's an example of working code that builds an Ubuntu 11.10 Oneiric EBS boot AMI using Canonical's downloadable image:

https://github.com/alestic/alestic-git/blob/master/bin/alestic-git-build-ami

Leave a comment

Ubuntu AMIs

Ubuntu AMIs for EC2:


More Entries

EC2 create-image Does Not Fully "Stop" The Instance
The EC2 create-image API/command/console action is a convenient trigger to create an AMI from a running (or stopped) EBS boot instance. It takes a snapshot of the instance’s EBS volume(s)…
Finding the Region for an AWS Resource ID
use concurrent AWS command line requests to search the world for your instance, image, volume, snapshot, … Background Amazon EC2 and many other AWS services are divided up into various…
Changing The Default "ubuntu" Username On New EC2 Instances
configure your own ssh username in user-data The official Ubuntu AMIs create a default user with the username ubuntu which is used for the initial ssh access, i.e.: ssh ubuntu@<HOST>…
Default ssh Usernames For Connecting To EC2 Instances
Each AMI publisher on EC2 decides what user (or users) should have ssh access enabled by default and what ssh credentials should allow you to gain access as that user.…
New c3.* Instance Types on Amazon EC2 - Nice!
Worth switching. Amazon shared that the new c3.* instance types have been in high demand on EC2 since they were released. I finally had a minute to take a look…
Query EC2 Account Limits with AWS API
Here’s a useful tip mentioned in one of the sessions at AWS re:Invent this year. There is a little known API call that lets you query some of the EC2…
Using aws-cli --query Option To Simplify Output
My favorite session at AWS re:Invent was James Saryerwinnie’s clear, concise, and informative tour of the aws-cli (command line interface), which according to GitHub logs he is enhancing like crazy.…
Reset S3 Object Timestamp for Bucket Lifecycle Expiration
use aws-cli to extend expiration and restart the delete or archive countdown on objects in an S3 bucket Background S3 buckets allow you to specify lifecycle rules that tell AWS…
Installing aws-cli, the New AWS Command Line Tool
consistent control over more AWS services with aws-cli, a single, powerful command line tool from Amazon Readers of this tech blog know that I am a fan of the power…
Using An AWS CloudFormation Stack To Allow "-" Instead Of "+" In Gmail Email Addresses
Launch a CloudFormation template to set up a stack of AWS resources to fill a simple need: Supporting Gmail addresses with “-” instead of “+” separating the user name from…
New Options In ec2-expire-snapshots v0.11
The ec2-expire-snapshots program can be used to expire EBS snapshots in Amazon EC2 on a regular schedule that you define. It can be used as a companion to ec2-consistent-snapshot or…
Replacing a CloudFront Distribution to "Invalidate" All Objects
I was chatting with Kevin Boyd (aka Beryllium) on the ##aws Freenode IRC channel about the challenge of invalidating a large number of CloudFront objects (35,000) due to a problem…
Email Alerts for AWS Billing Alarms
using CloudWatch and SNS to send yourself email messages when AWS costs accrue past limits you define The Amazon documentation describes how to use the AWS console to monitor your…
Cost of Transitioning S3 Objects to Glacier
how I was surprised by a large AWS charge and how to calculate the break-even point Glacier Archival of S3 Objects Amazon recently introduced a fantastic new feature where S3…
Running Ubuntu on Amazon EC2 in Sydney, Australia
Amazon has announced a new AWS region in Sydney, Australia with the name ap-southeast-2. The official Ubuntu AMI lookup pages (1, 2) don’t seem to be showing the new location…
Save Money by Giving Away Unused Heavy Utilization Reserved Instances
You may be able to save on future EC2 expenses by selling an unused Reserved Instance for less than its true value or even $0.01, provided it is in the…
Installing AWS Command Line Tools from Amazon Downloads
When you need an AWS command line toolset not provided by Ubuntu packages, you can download the tools directly from Amazon and install them locally. In a previous article I…
Convert Running EC2 Instance to EBS-Optimized Instance with Provisioned IOPS EBS Volumes
Amazon just announced two related features for getting super-fast, consistent performance with EBS volumes: (1) Provisioned IOPS EBS volumes, and (2) EBS-Optimized Instances. Starting new instances and EBS volumes with…
Which EC2 Availability Zone is Affected by an Outage?
Did you know that Amazon includes status messages about the health of availability zones in the output of the ec2-describe-availability-zones command, the associated API call, and the AWS console? Right…
Installing AWS Command Line Tools Using Ubuntu Packages
See also: Installing AWS Command Line Tools from Amazon Downloads Here are the steps for installing the AWS command line tools that are currently available as Ubuntu packages. These include:…
Ubuntu Developer Summit, May 2012 (Oakland)
I will be attending the Ubuntu Developer Summit (UDS) next week in Oakland, CA. ┬áThis event brings people from around the world together in one place every six months to…
Uploading Known ssh Host Key in EC2 user-data Script
The ssh protocol uses two different keys to keep you secure: The user ssh key is the one we normally think of. This authenticates us to the remote host, proving…
Seeding Torrents with Amazon S3 and s3cmd on Ubuntu
Amazon Web Services is such a huge, complex service with so many products and features that sometimes very simple but powerful features fall through the cracks when you’re reading the…
CloudCamp
There are a number of CloudCamp events coming up in cities around the world. These are free events, organized around the various concepts, technologies, and services that fall under the…
Use the Same Architecture (64-bit) on All EC2 Instance Types
A few hours ago, Amazon AWS announced that all EC2 instance types can now run 64-bit AMIs. Though t1.micro, m1.small, and c1.medium will continue to also support 32-bit AMIs, it…
ec2-consistent-snapshot on GitHub and v0.43 Released
The source for ec2-conssitent-snapshot has historically been available here: ec2-consistent-snapshot on Launchpad.net using Bazaar For your convenience, it is now also available here: ec2-consistent-snapshot on GitHub using Git You are…
You Should Use EBS Boot Instances on Amazon EC2
EBS boot vs. instance-store If you are just getting started with Amazon EC2, then use EBS boot instances and stop reading this article. Forget that you ever heard about instance-store…
Retrieve Public ssh Key From EC2
A serverfault poster had a problem that I thought was a cool challenge. I had so much fun coming up with this answer, I figured I’d share it here as…
Running EC2 Instances on a Recurring Schedule with Auto Scaling
Do you want to run short jobs on Amazon EC2 on a recurring schedule, but don’t want to pay for an instance running all the time? Would you like to…
AWS Virtual MFA and the Google Authenticator for Android
Amazon just announced that the AWS MFA (multi-factor authentication) now supports virtual or software MFA devices in addition to the physical hardware MFA devices like the one that’s been taking…