Skip to content

Instantly share code, notes, and snippets.

@rubiojr
Created November 29, 2011 17:15
Show Gist options
  • Save rubiojr/1405573 to your computer and use it in GitHub Desktop.
Save rubiojr/1405573 to your computer and use it in GitHub Desktop.
Create KVM guest using fog/libvirt and a QCOW2 template
require 'fog'
require 'net/ssh'
require 'net/scp'
def upload_file(host, user, password, source, dest, print_progress = true)
Net::SSH.start(host, user, :password => password) do |ssh|
puts "Uploading file... (#{File.basename(source)})"
ssh.scp.upload!(source, dest) do |ch, name, sent, total|
if print_progress
print "\rProgress: #{(sent.to_f * 100 / total.to_f).to_i}% completed"
end
end
end
puts if print_progress
end
client = Fog::Compute.new({
:provider => "libvirt" ,
:libvirt_uri => "qemu+ssh://root@blackops/system"
})
require 'pp'
#
# List VM names
# not required, just demoing
client.servers.each do |s|
puts s.name
end
#
# List pools info
# not required, just demoing
#
client.pools.all.each do |p|
puts p.name
puts p.uuid
puts p.capacity
puts p.allocation
puts p.capacity - p.allocation # Free Space
end
#
# Create a test volume
# not required, just demoing
#
client.volumes.create :name => 'test-vol-foo.qcow2',
:allocation => "#{File.size('centos5-jeos-ip-info.qcow2')/1024/1024}M",
:capacity => '4G',
:format_type => 'qcow2',
:pool_name => 'default'
#
# create the domain/guest with a 10G volume (sparse/thin)
#
s = client.servers.create :name => 'fog-test',
:volume_allocation => "#{File.size('centos5-jeos-ip-info.qcow2')/1024/1024}M",
:volume_capacity => '10G',
:volume_format_type => 'qcow2',
#:autostart => true, # Starting guest automatically
:volume_pool_name => 'default'
#
# Upload our template to replace de volume created with servers.create
#
upload_file('blackops', 'root', '', 'centos5-jeos-ip-info.qcow2', '/var/lib/libvirt/images/fog-test.qcow2')
#
# Start the guest
#
s.start
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment