Skip to content

Instantly share code, notes, and snippets.

@rubiojr
Created September 4, 2012 18:52
Show Gist options
  • Save rubiojr/3624973 to your computer and use it in GitHub Desktop.
Save rubiojr/3624973 to your computer and use it in GitHub Desktop.
Convert QCow2 images to AMI/AKI/ARI (OpenStack compatible)
#!/usr/bin/env ruby
require 'fileutils'
source = File.expand_path ARGV[0]
tmpdir = "/tmp/#{File.basename(source, '.qcow2')}"
root_img = "#{tmpdir}/root.img"
root_dev = "/dev/nbd1p2"
root_source = ""
boot_source = ""
FileUtils.mkdir_p "#{tmpdir}/root"
puts "nbd connect..."
`qemu-nbd -c /dev/nbd1 #{source}`
loop { break if File.exist?(root_dev); sleep 1 }
puts "Mount partitions..."
Dir["/dev/nbd1p*"].each do |d|
dir = "#{tmpdir}/source/#{File.basename(d)}"
FileUtils.mkdir_p dir
puts "Mounting #{dir}"
`mount -o loop #{d} #{dir}`
end
puts "Identifiying partitions..."
Dir["#{tmpdir}/source/*"].each do |d|
if File.exist?(Dir[d + "/boot/vmlinuz*"].first || '')
puts "boot partition found: #{d}"
boot_source = d
end
if File.exist?(Dir[d + "/vmlinuz*"].first || '')
puts "boot partition found: #{d}"
boot_source = d
end
if File.directory?(d + "/usr")
root_source = d
puts "root partition found: #{d}"
end
end
if File.directory? "#{boot_source}/boot"
FileUtils.cp Dir["#{boot_source}/boot/vmlinuz*"].last, "#{tmpdir}/aki"
FileUtils.cp Dir["#{boot_source}/boot/initr*"].last, "#{tmpdir}/ari"
else
FileUtils.cp Dir["#{boot_source}/vmlinuz*"].last, "#{tmpdir}/aki"
FileUtils.cp Dir["#{boot_source}/initr*"].last, "#{tmpdir}/ari"
end
`dd if=/dev/zero of=#{root_img} bs=4k count=0 seek=998000`
`mkfs.ext4 -F -L cloudimg-rootfs #{root_img}`
`mount -o loop #{root_img} #{tmpdir}/root`
puts "rsync root FS from #{root_source} to #{tmpdir}/root/ ..."
`rsync -av #{root_source}/ #{tmpdir}/root/`
FileUtils.rm_rf Dir["#{tmpdir}/root/boot/*"]
puts "Cleaning up..."
`nbd-client -d /dev/nbd1`
Dir["#{tmpdir}/source/*"].each do |d|
puts "Umount #{d}"
`umount #{d}`
end
`umount #{tmpdir}/root`
FileUtils.rm_rf "#{tmpdir}/source/"
FileUtils.rm_rf "#{tmpdir}/root/"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment