Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Quick OpenStack Server Create with ruby Fog
#!/usr/bin/env ruby
#
# Before we start, make sure you have Essex support in Fog
#
# Essex support has not been merged into upstream Fog so you'll need
# a custom ruby fog build to run through the examples
#
require 'fog'
require 'pp'
require 'highline/import'
require 'colored'
%w{OS_PASSWORD OS_USERNAME OS_AUTH_URL_FOG}.each do |env|
if ENV[env].nil?
$stderr.puts "Missing #{env} environment variable."
exit 1
end
end
# Connect and authenticate
#
conn = Fog::Compute.new({
:provider => 'OpenStack',
:openstack_api_key => ENV['OS_PASSWORD'],
:openstack_username => ENV["OS_USERNAME"],
:openstack_auth_url => ENV["OS_AUTH_URL_FOG"],
:openstack_tenant => ENV["OS_USERNAME"]
#:connection_options => { :ssl_verify_peer => false }
})
# 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
#
if ARGV[0]
image_name = ARGV[0]
else
image_name = ask("Image?".bold.magenta + " ") { |q| q.default = 'ubuntu-precise-amd64' }
end
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
# FIXME: raises an exception for some reason. Looks like it expects a public ip
# associated
#server = conn.servers.bootstrap :name => "rubiojr-#{Time.now.strftime '%Y%m%d'}",
# :image_ref => image.id,
# :flavor_ref => flavor.id
# This is equivalent but better for faster async creation since waiting
# for ready? is optional
#
puts "#{'Creating server'.yellow} from image #{image.name}..."
server = conn.servers.create :name => "rubiojr-#{Time.now.strftime '%Y%m%d-%H%M%S'}",
:image_ref => image.id,
:flavor_ref => flavor.id,
:key_name => 'my-foo-keypair'
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'.yellow}..."
ip = conn.addresses.create
end
puts "#{'Associate IP'.yellow} #{ip.ip}..."
ip.server = server
puts "#{'Server:'.yellow} #{server.name} #{'IP:'.yellow} #{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.