如何将数组作为参数传递给人偶 类

How to pass array as parameter to puppet classes

如何将参数传递给木偶 class。 例如,我有这个代码:

class testlogging {
  file { '/home/amo/testloggingfile':
    ensure => 'present',
    source => 'puppet:///modules/testlogging/testlogging',
  }
}

我想要做的是将 filenames/paths 的数组作为参数传递给此 class。

您确实应该熟悉文档,尤其是 Language Reference. Its section on classes 讨论了如何定义 class 以便它接受参数,以及如何指定所需的参数值。

但是,简而言之,模块 mymodule 中接受必需参数的 class myclass 的定义采用以下形式:

class mymodule::myclass($param) {
    # ...
}

您通常会通过自动数据绑定将值绑定到 class 的参数,就所有意图和目的而言,这意味着 Hiera。要为 Hiera 的默认 yaml 后端指定一个数组值来处理,数据将包含以下内容:

---
mymodule::myclass::param:
  - '/path/to/file1'
  - '/path/to/file2'

关于如何配置 Puppet 和 Hiera 的完整解释对于这个论坛来说过于宽泛。

John Bollinger 的答案是推荐的答案。如果你想不使用 Hiera yaml 后端,你可以写一个 define type

class myclass {
 # Create a define type, that will take $name as the file
 # You provide $src for each file
 define mydefine ($src) {
   file { $name :
     ensure => present,
     source => "puppet:///modules/<mymodule>/$src",
   }
  }

  # Use two arrarys, one for file names and other for source
  $filearray=["/path/to/file1","/path/to/file2"]
  $filesrc=["source1","source2"]

  # Loop over the array
  each($filearray) | $index, $value | {
   mydefine{ $value :
      src => $filesrc[$index],
    }
 }