Skip to content

Instantly share code, notes, and snippets.

@stathy
Created May 11, 2013 16:32
Show Gist options
  • Save stathy/5560501 to your computer and use it in GitHub Desktop.
Save stathy/5560501 to your computer and use it in GitHub Desktop.
Opscode Chef API directly for setting override env attributes so newly bootstrapped nodes can pickup new artifacts for deployment.
#!/opt/opscode/embedded/bin/ruby
#
#!/opt/opscode/embedded/bin/ruby
#
require 'chef/environment'
require 'chef/knife'
require 'chef/knife/cookbook_upload'
require 'chef'
require 'digest'
require 'fileutils'
Chef::Log.level = :info
class BootstrapError < StandardError; end
artifact_path = "/var/www/html/artifacts/#{ENV['JOB_NAME']}/#{ENV['BUILD_NUMBER']}/dbapp.war"
artifact_url = "http://chef.localdomain:10080/artifacts/#{ENV['JOB_NAME']}/#{ENV['BUILD_NUMBER']}/dbapp.war"
Dir.chdir("/var/www/html/artifacts/#{ENV['JOB_NAME']}/#{ENV['BUILD_NUMBER']}") do
checksum = Digest::SHA256.file( artifact_path ).hexdigest
Chef::Log.info( %Q(Checksum for #{artifact_path} is "#{checksum}") )
Chef::Config.from_file( %Q(#{ENV['HOME']}/.chef/knife.rb) )
Chef::Log.info( %Q(Artifact source location is "#{artifact_url}") )
# If we want distinct environments per build, uncomment
ce = "#{ENV['JOB_NAME']}-#{ENV['BUILD_NUMBER']}"
env_obj = Chef::Environment.new
env_obj.name( ce )
env_obj.override_attributes( { 'apps' => { 'dbapp' => {} } } )
begin
env_obj = Chef::Environment.load( ce )
rescue Net::HTTPServerException => e
raise e unless e.response.code == "404"
env_obj.default_attributes['created_by'] ||= 'Jenkins'
env_obj.default_attributes['created_date'] ||= Time.new.strftime("%Y_%m_%d-%H:%M:%S")
env_obj.create
end
env_obj.override_attributes['apps']['dbapp']['source'] = artifact_url
env_obj.override_attributes['apps']['dbapp']['checksum'] = checksum
env_obj.save
end
Dir.chdir("/var/www/html/artifacts/#{ENV['JOB_NAME']}") do
last_build_to_keep = ENV['BUILD_NUMBER'].to_i - 2
Dir.foreach('.') do |b_dir|
# Chef::Log.info( %Q(Last build to keep #{last_build_to_keep}, Remove "#{b_dir}"?) )
if b_dir.to_i > 0 && b_dir.to_i < last_build_to_keep then
Chef::Log.warn( %Q(Removing build dir "#{b_dir}") )
FileUtils.rm_rf( b_dir )
end
end
end
__END__
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment