Search code examples
rubyfunctionfile-iopuppet

Add a custom function in puppet


I'm trying to port a Ruby script in puppet. As far as I know, the only way to achieve that is by creating a custom function in a module. Feel free to tell me if there's another way. I tried my first test as shown on https://docs.puppetlabs.com/guides/custom_functions.html , I declared a new module in:

/etc/puppet/modules/custom_module

and edited a new function file called /etc/puppet/modules/custom_module/lib/puppet/parser/functions/newfunction with this code:

module Puppet::Parser::Functions
    newfunction(:write_line_to_file) do |args|
            filename = args[0]
            str = args[1]
            File.open(filename, 'a') {|fd| fd.puts str }
    end
end

Then I used in this manifest /etc/puppet/environments/desarrollo/manifests/des.pp with this content:

node "develserver" {
        write_line_to_file('/tmp/some_file', "Hello world!")
}

And finally when I run a puppet agent -tod it shows me the following error:

Error: Could not retrieve catalog from remote server: Error 400 on SERVER: Unknown function write_line_to_file at /etc/puppet/environments/desarrollo/manifests/des.pp:5 on node develserver

What am I doing wrong?


Solution

  • The immediate problem is likely the missing .rb extension on your function file name.

    Keep in mind that the Ruby code is run on the master during catalog compilation. If you want Puppet to take action on the agent side, you cannot use custom functions. You will have to write a custom Resource Type (and often a Provider) to do that.