Currently I want to create an md5 hash from an argument. Then I want to write the hash into a file (the path is another argument).
That is the custom function:
module Puppet::Parser::Functions
newfunction(:write_line_to_file) do |args|
require 'md5'
filename = args[0]
str = MD5.new(lookupvar(args[1])).to_s
File.open(filename, 'a') {|fd| fd.puts str }
end
end
And the call in the puppet manifest:
write_line_to_file('/tmp/some_hash', "Hello world!")
The result I get is a file and the content is not the hash but the original string. (In the example Hello World!)
I know that this custom function has no practical use. I just want to understand how the md5 hash works.
---UPD---
new Function (it works properly):
require 'digest'
module Puppet::Parser::Functions
newfunction(:lxwrite_line_to_file) do |args|
filename = args[0]
str = Digest::MD5.hexdigest args[1]
File.open(filename, 'w') {|fd| fd.puts str }
end
end
Which ruby you are using?
In Ruby 2.0+ there is a Digest
module (documentation here) - why you don't use it instead?.
You can use any hash, available in Digest
, like this:
Digest::MD5.digest '123'
=> " ,\xB9b\xACY\a[\x96K\a\x15-#Kp"
or use hexdigest
if you prefer hex representation
Digest::MD5.hexdigest '123'
=> "202cb962ac59075b964b07152d234b70"
There are also other hash-functions available there:
Digest::SHA2.hexdigest '123'
=> "a665a45920422f9d417e4867efdc4fb8a04a1f3fff1fa07e998e86f7f7a27ae3"