Skip to content

Instantly share code, notes, and snippets.

@mvidner mvidner/quick_vm.rb forked from rubiojr/quick_vm.rb
Created Oct 17, 2012

Embed
What would you like to do?
Quick OpenStack Server Create with ruby Fog
#!/usr/bin/env ruby
#
require 'rubygems'
require 'fog'
%w{OS_PASSWORD OS_USERNAME OS_AUTH_URL}.each do |env|
if ENV[env].nil?
$stderr.puts "Missing #{env} environment variable."
exit 1
end
end
if ENV['OS_KEY_NAME'].nil?
$stderr.puts "Warning, no OS_KEY_NAME specified, you may not be able to log in"
end
# https://github.com/fog/fog/issues/1210
openstack_auth_url = ENV["OS_AUTH_URL"]
openstack_auth_url += '/tokens' unless openstack_auth_url.end_with? '/tokens'
# Connect and authenticate
#
conn = Fog::Compute.new({
:provider => 'OpenStack',
:openstack_api_key => ENV['OS_PASSWORD'],
:openstack_username => ENV["OS_USERNAME"],
:openstack_auth_url => openstack_auth_url,
:openstack_tenant => ENV["OS_TENANT_NAME"],
# They come in ca-certificates.rpm on SUSE
:connection_options => { :ssl_ca_path => '/etc/ssl/certs' }
})
# Find the server flavor we want.
# m1.tiny has 512 MB of RAM and no additional ephemeral storage
#
flavor = conn.flavors.find { |f| f.name == 'm1.tiny' }
# Find the image we want
#
image_name = ARGV[0] || "openSUSE-12.2-64-minimal"
image = conn.images.find { |i| i.name == image_name }
if image.nil?
$stderr.puts "Image #{image_name} not found. Aborting."
exit 1
end
# Create the server
#
puts "Creating server from image #{image.name}..."
server = conn.servers.create :name => "quick_vm-#{Time.now.strftime '%Y%m%d-%H%M%S'}",
:image_ref => image.id,
:flavor_ref => flavor.id,
:key_name => ENV['OS_KEY_NAME'] # nonstandard ENV
server.wait_for { ready? }
# Associate a public IP to the server
# Create if there are no floating ips available
#
ip = conn.addresses.find { |ip| ip.instance_id.nil? }
if ip.nil?
puts 'Creating IP'
ip = conn.addresses.create
end
puts "Associate IP #{ip.ip}..."
ip.server = server
puts "Server: #{server.name} IP: #{ip.ip}"
# Cleanup
#
#ip.destroy
#server.destroy
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.