Skip to content

Instantly share code, notes, and snippets.

@ohadlevy
Created April 11, 2011 09:59
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ohadlevy/913305 to your computer and use it in GitHub Desktop.
Save ohadlevy/913305 to your computer and use it in GitHub Desktop.
#!/usr/bin/ruby
require "rubygems"
require "rest_client"
require "json"
require "uri"
fqdn = ARGV[0] || raise("Must define a fqdn")
mac = ARGV[1] || raise("Must define a mac")
ip = ARGV[2] || raise("Must define a IP")
#TODO: add support for subnets and auto IP fetching
start = Time.now
foreman_url = "http://0.0.0.0:3000"
foreman_user = "admin"
foreman_pass = "changeme"
puppet_env = "production"
domain_name = "lab"
hostgroup_name = "common"
host_arch = "x86_64"
media_name = "Fedora Mirror"
os_name = "Fedora 14"
ptable_name = "Fedora default"
parameters = {:name => "activation_key", :value =>"123123xxxxxxx"}
#TODO: Add support for more than one paramter
# define defaults for restful connectivity to Foreman
@foreman = RestClient::Resource.new foreman_url,{ :user => foreman_user, :password => foreman_pass,
:headers => { :accept => :json, :content_type => :json }}
t=Time.now
# a simple helper to get the real ID values from foreman (translates name to ID)
def helper(url, title, type = nil, args = %w{ name id })
t=Time.now
type ||= url.gsub("\/","").chomp("s")
print "Asking Foreman for its #{title} #{type} ID..."
hash = JSON.parse(@foreman[URI.escape(url)].get.body)
printf "done in %5.2f seconds\n", Time.now - t
r = hash.select{|t| t[type][args.first] == title}.first
r[type][args.last]
end
env_id = helper("/environments", puppet_env)
os_id = helper("/operatingsystems", os_name)
arch_id = helper("/architectures",host_arch)
media_id = helper("/media",media_name, "medium")
domain_id = helper("/domains",domain_name)
ptable_id = helper("/ptables",ptable_name)
hostgroup_id = helper("/hostgroups",hostgroup_name)
payload = {:host => {
:name => fqdn, :mac => mac, :ip => ip,
:environment_id => env_id, :architecture_id => arch_id, :domain_id => domain_id, :medium_id => media_id,
:operatingsystem_id => os_id, :ptable_id => ptable_id,
:host_parameters_attributes => { Time.now.to_i => parameters.update(:nested => "") },
:build => true, :hostgroup_id => hostgroup_id, :comment => "Added via Batch"
}}.to_json
begin
t=Time.now
print "Creating the Host at Foreman..."
$stdout.flush
@foreman["/hosts"].post payload
printf "done in %5.2f seconds\n", Time.now - t
puts
rescue => e
warn "ERROR: #{e.response}"
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment