Search code examples
rubypuppet

Function to read role, environment file in masterless puppet


I'm working with Puppet 4.5 in masterless configuration and am trying to create a Puppet function to read a simple config file that assigns roles and environments. I don't have any integration with hiera/facter that I can change.

The file format is:

host1::java_app_node::qa
host2::nodejs_app_node::prod

The Puppet function that will read this file is in a module called homebase. I want to function to return a hash or array of hashes that split the config values. This will let me use them in templates.

In modules/homebase/manifests/init.pp I define:

$role_file = 'puppet://role.lst'

I then created modules/homebase/functions/get_roles.pp as follows:

function homebase::get_roles() {
    $func_name = 'homebase::get_roles()'

    if ! File.exists?($::homebase::role_file) {
        fail("Could not find #{$::homebase::role_file}")
    }

    hosts = { }
    File.open($::homebase::role_file).each |line| {
        parts = line.split(/::/)
        hosts[parts[0]] = { 'host' => parts[0], 'role' => parts[1], 'env' => parts[2] }
    }
    return hosts
}

In other classes, I then want to call:

class myapp {
    $servers = homebase::get_roles().each | k, v | { 
         $v['host'] if $v['role'] =~ /myapp/ && $v['env'] == $environment
    }    

    file { 'myapp.cfg':
        ensure => file,
        path => '/opt/myapp/myapp.cfg',
        source => template("/myapp/myapp.cfg.erb"),
        mode => '0644',
        owner => myuser,
        group => myuser,
    }

}

Seems like there would be a better way to do this. Am I completely off base?


Solution

  • There turned out to be a much easier way to this rather than try to create a function to read a non-standard configuration file. Instead, I used a site.pp file to create node {} entries. I also parameterized the myapp class to take inputs based on the node.

    So my site.pp looks like:

    node 'server1.mydomain', 'server2.mydomain' {
      $myvar = [ 'val1', 'val2' ]
      class { 'myapp':
         values => $myvar
      }
    }
    

    This could probably be improved. One of the issues is with a non-Puppet configuration file I was able to also able to control execution in my bash wrapper script. Much of the need for that went away when, though, with the node definitions.