Skip to content

Instantly share code, notes, and snippets.

@xorpaul
Created October 15, 2013 14:20
Show Gist options
  • Save xorpaul/6992287 to your computer and use it in GitHub Desktop.
Save xorpaul/6992287 to your computer and use it in GitHub Desktop.
Add stat_file so that it is possible to not needlesly push fats for host #{certname}, because time of last fact push >= host fact yaml mtime!
def upload_facts(certname, filename)
  # Temp file keeping the last run time
  stat = stat_file(certname)
  puts "stat = #{stat}" if $debug
  print "stat_file #{stat} exists!" if File.exists?(stat)
  last_run = File.exists?(stat) ? File.stat(stat).mtime.utc : Time.now - 365*24*60*60
  last_fact = File.stat(filename).mtime.utc
  if last_fact > last_run
    begin
      uri = URI.parse("#{url}/api/hosts/facts")
      req = Net::HTTP::Post.new(uri.request_uri)
      req.add_field('Accept', 'application/json,version=2' )
      req.content_type = 'application/json'
      req.body         = build_body(certname, filename).to_json
      res              = Net::HTTP.new(uri.host, uri.port)
      res.use_ssl      = uri.scheme == 'https'
      if res.use_ssl?
        if SETTINGS[:ssl_ca] && !SETTINGS[:ssl_ca].empty?
          res.ca_file = SETTINGS[:ssl_ca]
          res.verify_mode = OpenSSL::SSL::VERIFY_PEER
        else
          res.verify_mode = OpenSSL::SSL::VERIFY_NONE
        end
        if SETTINGS[:ssl_cert] && !SETTINGS[:ssl_cert].empty? && SETTINGS[:ssl_key] && !SETTINGS[:ssl_key].empty?
          res.cert = OpenSSL::X509::Certificate.new(File.read(SETTINGS[:ssl_cert]))
          res.key  = OpenSSL::PKey::RSA.new(File.read(SETTINGS[:ssl_key]), nil)
        end
      end
      res.start { |http| http.request(req) }
      cache(certname, "Facts from this host was last push to foreman at #{Time.now}\n")
    rescue => e
      raise "Could not send facts to Foreman: #{e}"
    end
  else
    puts "\nNot pushing fats for host #{certname}, because time of last fact push >= host fact yaml mtime!" if $debug
  end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment