Hiera - 来自哈希的变量

问题描述

我在 Hiera 的表现真的很糟糕,我只是似乎不明白。我不知道这是否可行,但我想为我的班级提供一个哈希值,例如:

modules::unit::filemode::config
 - /usr/bin/ls,root,0775

并将其映射到

file { "$filename":
   owner => $owner,group => $group,mode  => $mode
}

我尝试过使用哈希和 $config.each,但我似乎无法弄清楚。

有什么指点吗? :) 谢谢

解决方法

我想为我的班级提供一个哈希值,例如:

modules::unit::filemode::config
 - /usr/bin/ls,root,0775

这不是有效的 YAML,而且您似乎试图与键 modules::unit::filemode::config 关联的值看起来不像哈希。哈希将值与键相关联,那么键在哪里?

从预期用途来看,我猜你想要更像这样的东西:

# The value is one hash with keys name,owner,group,and mode
modules::unit::filemode::config:
  path: '/usr/bin/ls'
  owner: 'root'
  group: 'root'
  mode: '0775'

或者像这样:

# The value is hash of hashes; the outer hash has file names for keys,# and the inner ones have keys owner,and mode
modules::unit::filemode::config2:
  '/usr/bin/ls':
    owner: 'root'
    group: 'root'
    mode: '0775'
  '/maybe/another':
    owner: 'luser'
    group: 'root'
    mode: '0644'

其中任何一个都可以为类参数 $modules::unit::filemode::config 提供数据:

class modules::unit::filemode(
  Hash $config
) {
  # ...
}

前一种类型的数据为单个文件提供信息,通过键显式访问哈希成员最有意义:

file { $config['path']:
  owner => $config['owner'],group => $config['group'],mode  => $config['mode'],}

或者,因为我仔细选择了与 File 资源属性(包括 path)的名称匹配的哈希键,您可以将其缩写为:

file { $config['path']:
  * => $config,}

在这种情况下迭代成员没有多大意义,因为它们没有什么个人意义,而且它们只是在语法上而不是语义上具有可比性。

后一种数据布局允许提供有关多个文件的信息,一个用于外部散列的每个元素。这些外部成员在语义上是可比的,迭代它们是使用数据的一种可能方式,可能是这样的:

$config2.each |$path,$props| {
  file { $path:
    * => $props,}
}

这声明了一个 File 资源对应于(外部)散列的每个元素。