Skip to content

Instantly share code, notes, and snippets.

@majormoses
Last active November 8, 2017 04:19
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save majormoses/fbdb833a0797624c628ef12b0aa30040 to your computer and use it in GitHub Desktop.
Save majormoses/fbdb833a0797624c628ef12b0aa30040 to your computer and use it in GitHub Desktop.
Example of how to restart a service, wait for it to come up, and then do more things
# drop in a template and immediately restart jenkins
template "#{node['jenkins']['master']['home']}/config.xml" do
source 'config.xml.erb'
variables({
'github_client_id' => <REDACTED>,
'github_client_secret' => <REDACTED>
})
owner node['jenkins']['master']['user']
group node['jenkins']['master']['group']
mode '0600'
notifies :restart, 'service[jenkins-service]', :immediately
end
end
# Make sure jenkins is entirely up & functioning normally
cc_jenkins_verify_url_reachability 'verify_jenkins_is_running' do
url "#{<REDACTED>}://<REDACTED>:#{<REDACTED>}/"
retry_count 10
retry_delay_secs 10
username <REDACTED>
password lazy { <REDACTED> }
secure <REDACTED>
end
# do more things
use_inline_resources
# Will attempt to do a GET request to the specified url retry_count times with a delay of
# retry_delay_secs in between attempts. A successful connection means an HTTP response was
# returned with a code matching expected_http_status
# TODO: add https support and methods other than GET
action :verify do
attempt_num = 1
uri = URI.parse(@new_resource.url)
if uri.scheme != 'http'
raise "Unsupported scheme: #{uri.scheme}. Currently only http scheme is supported"
end
http = Net::HTTP.new(uri.host, uri.port)
request = Net::HTTP::Get.new(uri.path)
if @new_resource.secure
request.basic_auth(@new_resource.username, @new_resource.password)
end
begin
Chef::Log.info("trying to connect to #{@new_resource.url} (attempt #{attempt_num}/#{@new_resource.retry_count})")
response = http.request(request)
if response.code != @new_resource.expected_http_status.to_s
raise "Unexpected status: #{response.code}"
end
Chef::Log.info("Connection to #{@new_resource.url} successfully established")
rescue StandardError => e
Chef::Log.warn("attempt #{attempt_num}/#{@new_resource.retry_count} to connect to #{@new_resource.url} failed")
if attempt_num == @new_resource.retry_count
raise e, "Failed to connect to #{@new_resource.url}"
end
attempt_num += 1
sleep(@new_resource.retry_delay_secs)
retry
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment