Skip to content

Instantly share code, notes, and snippets.

@stathy
Created May 11, 2013 16:30
Show Gist options
  • Save stathy/5560492 to your computer and use it in GitHub Desktop.
Save stathy/5560492 to your computer and use it in GitHub Desktop.
Opscode Chef API interaction with Ruby to bootstrap new nodes generated by GCE within a Jenkins run, set attributes and assign roles to newly provisioned instances for configuration and application deployment.
#!/usr/local/rvm/rubies/ruby-1.9.3-p362/bin/ruby
#
require 'ridley'
require 'pathname'
require 'openssl'
require 'digest'
require 'json'
class BootstrapError < StandardError; end
URL = %Q(https://api.opscode.com/organizations/stathy)
ORG = Pathname.new(URL).basename
conn = Ridley.connection({
server_url: URL,
organization: ORG,
client_name: 'jenkins_stathy',
client_key: %Q(#{ENV['HOME']}/.chef/jenkins@opscode.com.pem),
validator_client: "stathy-validator",
validator_path: "#{ENV['HOME']}/.chef/stathy-validator.pem",
ssh: {
user: 'jenkins',
keys: "#{ENV['HOME']}/.ssh/google_compute_engine",
user_known_hosts_file: "/dev/null",
verify: false
}
})
Dir.chdir(ENV['WORKSPACE']) do
ce = "#{ENV['JOB_NAME']}-#{ENV['BUILD_NUMBER']}"
artifact_path = %Q(./dbapp/target/dbapp.war)
checksum = Digest::SHA256.file(artifact_path).hexdigest
artifact_url = %Q(http://commondatastorage.googleapis.com/stathy/#{ENV['JOB_NAME']}/#{ENV['BUILD_NUMBER']}/dbapp.war)
conn.sync do
if environment.find(ce).nil?
e_obj = environment.new
e_obj.name = ce
e_obj.set_override_attribute("chef_client.server_url", "https://api.opscode.com/organizations/stathy")
e_obj.set_override_attribute("chef_client.validation_client_name", "stathy-validator")
e_obj.set_override_attribute("apps.dbapp.owner", "nobody")
e_obj.set_override_attribute("apps.dbapp.group", "nobody")
e_obj.set_override_attribute("apps.dbapp.checksum", checksum)
e_obj.set_override_attribute("apps.dbapp.source", artifact_url)
environment.create(e_obj)
end
%w( db app1 lb ).each do |n|
cmd = %Q( I=( `gcutil getinstance dbapp-#{n} | grep 'external-ip' | sed 's/|//'g` ); echo ${I[1]} )
ip = `#{cmd}`.chomp
raise if ip.nil?
6.downto(1) do |i|
status = nil
begin
status = node.bootstrap(ip, {environment: ce, run_list: %W( role[base_centos] role[dbapp_#{n.gsub(/[0-9]+/,'')}] ), sudo: true, no_host_key_verify: true})
if status.has_errors?
raise BootstrapError.new("Error bootstrapping chef on #{ip}")
else
break
end
rescue BootstrapError => e
if i == 1
exit status.responses.last.exit_code
else
sleep(10)
end
end
end
end
end
end
__END__
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment