为数组中的每个项实例化一个类

时间:2014-04-21 16:23:05

标签: puppet nagios

Puppet Version: 3.2.4(Puppet Enterprise 3.0.1)

为了更好地支持配置文件中的nagios cfg_dircfg_file指令,我创建了以下类,每个选项对应一个:

# Class to add a cfg_dir to the nagios configuration file
class nagios::server::cfg_dir (
  $config_dir,
  $nagios_user,
  $nagios_group,
  $nagios_config_file = '/etc/nagios3/nagios.cfg',
)
{
  # Build the config dir
  file {$config_dir:
    ensure => directory,
    owner => $nagios_user,
    group => $nagios_group,
    mode => '0750',
  }

  # Append cfg_dir=$config_dir path to nagios.cfg file
  augeas { "cfg_dir=$config_dir in $nagios_config_file":
    incl => "$nagios_config_file",
    lens => 'NagiosCfg.lns',
    changes => "set cfg_dir/[last()+1] ${config_dir}",
    require => File[$nagios_config_file],
  }
}

尝试在nagios::server中使用此构造,我有:

# Set up config directories
each($cfg_dir) |$x| {
  class { 'nagios::server::cfg_dir':
    config_dir => $x,
    nagios_user => $nagios_user,
    nagios_group => $nagios_group,
    nagios_config_file => $nagios_config_file,
  }
}

理论上,应该为传递到nagios::server类的每个路径执行类实例化,如下所示:

class{'::nagios::server': cfg_dir => ['/etc/nagios.d','/etc/nagios/objects'] }

但是,我遇到了这个问题:

Error: Could not match |$x| at /tmp/vagrant-puppet-1/modules-2/nagios/manifests/server.pp:181 on node localhost.localdomain

有人可以提供使用each的工作示例吗?我对这个内置的木偶功能有多大的期待?

2 个答案:

答案 0 :(得分:1)

除了上面的一些代码语法问题,我发现这个构造只在future解析器中进行评估:

puppet apply --parser = future --modulepath ...

http://docs.puppetlabs.com/puppet/latest/reference/experiments_lambdas.html

仍然越过其他依赖性问题。我将使用什么模式来支持当前解析器而不是将来?自定义功能?

答案 1 :(得分:0)

我的后续问题的答案是使用已定义的类型:

http://docs.puppetlabs.com/learning/definedtypes.html

只需将上述代码从class更改为define,然后为$config_dir分配$target值,

define nagios::server::cfg_dir (
  $config_dir = $target,
  $nagios_user,
  $nagios_group,
  $nagios_config_file = '/etc/nagios3/nagios.cfg',
){...

您可以使用以下构造:

nagios::server::cfg_dir { '/etc/nagios.d/', '/etc/nagios/objects':
    nagios_user => 'nagios',
    nagios_group => 'nagios'
}

这解决了我的问题。