Search code examples
puppet

How to iterate on puppet? Or how to avoid it?


I have a global string variable that's actually an array of names:

"mongo1,mongo2,mongo3"

What I'm doing here is splitting them into an array using the "," as a delimiter and then feeding that array into a define to create all instances I need.

Problem is, every instance has a different port. I made a new stdlib function to get the index of a name in an array, and am feeding that to the port parameter.

This seems bad and I don't like having to alter stdlib.

So I'm wondering how I could do this using something like a nx2 array?

"mongo1,port1;mongo2,port2;mongo3,port3"

or two arrays

"mongo1,mongo2,mongo3" and "port1,port2,port3"

class site::mongomodule {
  class { 'mongodb':
    package_ensure => '2.4.12',
    logdir         => '/var/log/mongodb/'
  }

  define mongoconf () {
    $index = array_index($::site::mongomodule::mongoReplSetName_array, $name)

    mongodb::mongod { "mongod_${name}":
      mongod_instance => $name,
      mongod_port     => 27017 + $index,
      mongod_replSet  => 'Shard1',
      mongod_shardsvr => 'true',
    }
  }

  $mongoReplSetName_array = split(hiera('site::mongomodule::instances', undef), ',')

  mongoconf { $mongoReplSetName_array: }
}

the module I'm using is this one:

https://github.com/echocat/puppet-mongodb


using puppet 3.8.0


Solution

  • Hiera can give you a hash when you lookup a key, so you can have something like this in hiera:

    mongoinstances:
      mongo1:
        port: 1000
      mongo2:
        port: 1234
    

    Then you lookup the key in hiera to get the hash, and pass it to the create_resources function which will create one instance of a resource per entry in the hash.

    $mongoinstances = hiera('mongoinstances')
    create_resources('mongoconf', $mongoinstances)
    

    You will need to change mongoconf for this to work by adding a $port parameter. Each time you want to pass an additional value from hiera, just add it as a parameter to your defined type.