简体   繁体   中英

Iterate over an array of hashes in puppet

I have hiera data in puppet as follows:

elasticsearch::cluster_name: 'elasticsearch-dev'
elasticsearch::masterlist: [ "elasticsearchdev01.domain.com", "elasticsearchdev02.domain.com", "elasticsearchdev03.domain.com" ]
elasticsearch::kibanalist: [ "kibanadev01.domain.com" ]

And my manifest contains this:

  $masterlist = hiera('elasticsearch::masterlist')
  $kibanalist = hiera('elasticsearch::kibanalist')

  if ( $::fqdn in $masterlist ) or ( $::fqdn in $kibanalist ) {
    $cluster_name = hiera('elasticsearch::cluster_name')
  }

  else {
    notify { 'No cluster for node':
      message => "${::fqdn} is not configured to be in any cluster in the hiera data",
    }
  }

I would like to modify this to allow multiple clusters to be configured for a single environment, and I'm not sure of the best way to implement this. I want to be able to group the master lists with their corresponding cluster names, and then call the relevant cluster name for each node.

I think perhaps I need to use an array of hashes and iterate over it, but I don't know how to cover this in my manifest.

You would probably want to restructure your data as a Hash of Hashes:

elasticsearch::clusters:
  'elasticsearch-dev':
    masterlist: [ "elasticsearchdev01.domain.com", "elasticsearchdev02.domain.com", "elasticsearchdev03.domain.com" ]
    kibanalist: [ "kibanadev01.domain.com" ]

And then have in your manifests:

$clusters = hiera('elasticsearch::clusters')

$mycluster = $clusters.filter |$cluster, $data| {
  ($::fqdn in $data['masterlist']) or ($::fqdn in $data['kibanalist'])
}

if ($mycluster.empty) {
  notify { 'No cluster for node':
    message => "${::fqdn} is not configured to be in any cluster in the hiera data",
  }
}

$cluster_name = $mycluster.keys[0]
notice($cluster_name)

You might want to also consider replacing the deprecated hiera() call with lookup() and using $facts['networking']['fqdn'] instead of the legacy $::fqdn .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM