Thursday, January 16, 2014

Puppet and Hiera Hashes

Hiera data is great for separating code and data.
Within hiera one can put different types of variables:
- text
- arrays
- hashes

Working with text and arrays is easy for most Puppet users.

Hashes still seem to have some kind of magic.
This post tries to show you an idea on how to work with hashes in hiera.

we want ssh host keys in hiera to get added to a system.

First we are building our hiera data:

  - server1:
    alias: webserver
    key: erupeurzbgpeurhgfpuerfgp
    type: ssh-rsa
  - server2:
    alias: dbserver
    key: oeurzhgopeurzgbperuzfg
    type: ssh-dsa
  - server3:
    alias: proxy
    key: 346508365384
    type: ssh-rsa

One solution is to create a define and use the hash elements within an array.
The define would look like this:

define process_hostkeys () {
    ssh_key { $name:
        alias => $host_key[$name][alias],
        key => $host_key[$name][key],
        type => $host_key[$name][type],

So far so good. But... how do we get the elements from the hash?

Luckily puppet stdlib has the answer: there is a keys() function available.
The keys function extracts all keys from a hash and returns them as an array.

So in our case this will look like the following:

$host_array = keys($host_key)

And now we can use our define with this array variable:

process_hostkeys { $host_array: }

Due to the reason that we may use arrays in titles we are now happy.


No comments:

Post a Comment