Giving special treatment to the last entry when iterating over a Puppet hash

February 20, 2020 – Samuli Seppänen

When you're iterating over a hash you may end up having to treat the last hash entry differently. For example, if you're creating entries to a JSON file you should have "}," in between the entries until you reach the last entry, where you must have just "}" or JSON data will be invalid.

Now, hashes do not have indexes, nor does Puppet support variable reassignment along the lines of $x = $x +1, so you're out of luck trying to get the length and comparing that to a counter. So, you need some other way to detect when iteration has reached the last entry in the hash.

The solution is surprisingly simple: you just convert the keys of the hash into and array and get the last entry. So something like this in Puppet code:

$my_hash = { 'first'  => 'one',
             'second' => 'two', }

$last_entry = keys[$my_hash][-1]

Now you know the key of the last entry and can use it for conditional logic:

$my_hash.each |$entry| {
  if $entry[0] == $last_entry {
    # Do something
  } else {
    # Do something else
  }
}

...

Want to talk to an expert?

If you want to reach us, just send us a message or book a free call!
menucross-circle