Search code examples
puppet

How to read keys into array?


I am trying to read keys from a hiera json file into an array.

The json is as follows:

{
  "network::interfaces": {
    "eth0": {
      "ip": "10.111.22.10"
    },
    "eth1": {
      "ip": "10.111.22.11"
    },
    "eth2": {
      "ip": "10.111.22.12"
    }
  }
}

In my Puppet code, I am doing this:

$network_interfaces = hiera_array('network::interfaces')
notice($network_interfaces)

Which results in the following:

Notice: Scope(Class[Role::Vagrant]): {eth0 => {ip => 10.111.22.10}, eth2 => {ip => 10.111.22.11}, eth3 => {ip => 10.111.22.12}}

But what I want are just the interfaces: [eth0, eth1, eth2]

Can someone let me know how to do this?


Solution

  • The difference between hiera_array() and plain hiera() has to do with what happens when the requested key (network::interfaces in your case) is present at multiple hierarchy levels. It has very little to do with what form you want the data in, and nothing to do with selecting bits and pieces of data structures. hiera_array() requests an "array-merge" lookup. The more modern lookup() function refers to this as the "unique" merge strategy.

    It seems unlikely that an array-merge lookup is in fact what you want. In that case, the easiest thing to do is read the whole hash and extract the keys:

    $network_interfaces = keys(hiera('network::interfaces'))
    

    In Puppet 4 you'll need to use the keys() function provided by the puppetlabs/stdlib module. From Puppet 5 on, that function appears in core Puppet.