从数组创建参数?

时间:2015-12-17 19:58:56

标签: puppet theforeman

我是ruby的新手,我正在编写一个可以通过Foreman访问的木偶模块。

我将其编写为Foreman智能类参数使用,因此可以从Foreman Web控制台进行配置。

我试图了解如何为设备可能拥有的48个可能端口创建参数。而不是手动输入端口,我想知道是否可以动态地执行此操作。

例如,而不是:

class ciscobaseconfig (
  $interface_description_lan = 'A LAN interface'
) {
  interface {
   'FastEthernet 0/1':
      description => $interface_description_lan
  }
  interface {
   'FastEthernet 0/2':
      description => $interface_description_lan
  }
}

我想这样做:

class ciscobaseconfig (
  $interface_description_lan = 'A LAN interface',
) {
  interface {
    (0..48).each do |i|
    "FastEthernet 0/#{i}":
      description => $interface_description_lan
    end
  }
}

根据评论者的建议我试过了,但它不起作用:

class ciscobaseconfig (
  $interface_description_lan = 'A LAN interface',
) {

  arrInterfaces = Array(1..48)

  arrInterfaces.each{
    interface {
      |intNum| puts "FastEthernet 0/#{intNum}":
        description => $interface_description_lan
    }
  }
}

1 个答案:

答案 0 :(得分:3)

据我所知,你想要声明48个资源,使用基于资源索引的标题,以及所有具有相同参数值的资源。当然,这必须在Puppet DSL中实现,虽然它与Ruby有一些相似之处,但它不是Ruby。这似乎造成了一些混乱。

为此目的,安装puppetlabs-stdlib模块非常有用,它提供了各种有用的扩展功能。能够帮助我们的人是range()。如果安装了stdlib,这样的事情应该可以解决问题:

class ciscobaseconfig (
    $interface_description_lan = 'A LAN interface',
  ) {

  each(range('1', '48')) |portnum| {
    interface { "FastEthernet 0/${portnum}":
      description => $interface_description_lan
    }
  }
}

这确实假设你正在使用Puppet 4,或者Puppet 3使用未来的解析器。它也可以使用标准的Puppet 3解析器完成,但不能干净利落:

class ciscobaseconfig (
    $interface_description_lan = 'A LAN interface',
  ) {

  $portnums = split(inline_template("<%= (1..48).to_a.join(',') %>"), ',')
  $ifc_names = regsubst($portnums, '.*', 'FastEthernet 0/\0')

  interface { $ifc_names:
      description => $interface_description_lan
  }
}

特别注意,当一个数组作为资源标题给出时,它意味着你为数组的每个元素声明一个资源,所有元素都具有相同的参数。