Puppet Function: beats::get_checksum

Defined in:
lib/puppet/functions/beats/get_checksum.rb
Function type:
Ruby 4.x API

Summary

Retrieves beat SHA-512 Hash from a cache file, or get it from artifacts.elastic.co

Overview

beats::get_checksum(String $url, String $beat, String $version)String

Examples:

$checksum = get_checksum($url)

Parameters:

  • url (String)
  • beat (String)
  • version (String)

Returns:

  • (String)


14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
# File 'lib/puppet/functions/beats/get_checksum.rb', line 14

Puppet::Functions.create_function(:"beats::get_checksum") do
  dispatch :get_checksum do
    param 'String', :url
    param 'String', :beat
    param 'String', :version
    return_type 'String'
  end
  # the function below is called by puppet and and must match
  # the name of the puppet function above. You can set your
  # required parameters below and puppet will enforce these
  # so change x to suit your needs although only one parameter is required
  # as defined in the dispatch method.
  def get_checksum(url, beat, version)
    cache_dir = File.join(Puppet[:vardir], 'capsi-beats-hash-cache')
    cache = File.join(cache_dir, beat + version)

    if File.exist? cache
      File.read(cache)
    else
      checksum = http_get_checksum(url + ".sha512")

      FileUtils.mkdir_p(cache_dir)
      File.open(cache, 'w', 0o600) do |c|
        c.write(checksum)
      end
      File.chown(File.stat(Puppet[:vardir]).uid, nil, cache)
      File.chown(File.stat(Puppet[:vardir]).uid, nil, cache_dir)
      checksum
    end
  end

  def http_get_checksum(final_url)
    require 'open-uri'
    require 'timeout'

    begin
      result = Timeout::timeout(5) {
        uri = URI.parse(final_url)
        uri.read
      }
      sum = result[/[a-f0-9]{128}/]
      if sum == nil
        raise Puppet::ParseError, "Failed to get the checksum from artifacts.elastic.co: No checksum"
      end
      sum
    rescue Exception => e
      raise Puppet::ParseError, "Failed to get the checksum from artifacts.elastic.co: Timeout"
    end
  end
end