Search code examples
puppet

Using defined type to build array?


I currently have a class that looks something like this:

class mymodule (
  $files = [],
) {

file { '/my/file':
    ensure  => file,
    content => template(mymodule/mytemplate.erb)
  }
}

And a template:

files:
<% @files.each do |file| -%>
  - <%= file %>
<% end -%>

I'd like to move the files parameter to its own definition so I can more easily include the class closer to the base and define differen't files closer to node definitions like:

mymodule::file { '/my/file': }
mymodule::file { '/my/other_file': }

What is a good way to go about building the files array using defined types?


Solution

  • A structure like that is Very Hard to achieve using templates. There are two common ways to go about this instead.

    The concat module

    Using the puppetlabs-concat module, you can make your file consist of the concatenation of discreet snippets.

    class mymodule {
        concat { '/my/file': ensure => present }
    }
    
    define mymodule::file($content) {
        concat::fragment {
            target  => '/my/file',
            content => $content,
            order   => '50',
        }
    }
    

    Hiera

    If you can move your resources to Hiera with a create_resources construct, you can trivially extract the resource titles and use them in your template.