首页 > 解决方案 > 迭代 puppet 资源收集器

问题描述

我正在尝试开发一个具有已定义资源的木偶类,该资源为网站创建配置。

定义的资源必须做的一件事是将网站的 IP 地址分配给一个虚拟接口。由于项目的限制,这是通过 NetworkManager 完成的。

所以我必须生成一个像

[connection]
id=dummydsr
uuid=50819d31-8967-4321-aa34-383f4a658789
type=dummy
interface-name=dummydsr
permissions=

[ipv4]
method=manual
#IP Addresses come here
ipaddress1=1.2.3.4/32
ipaddress2=5.6.7.8/32
ipaddress3=8.7.6.5/32

[ipv6]
method=ignore

对于已定义资源的每个实例,都有一行 ipaddressX=... 。

我的问题是如何跟踪定义的资源被实例化的次数,以便我可以以某种方式增加一个计数器并生成 ipaddress 行。

或者对于每个实例化的已定义资源,将 IP 地址附加到一个数组中,稍后我可以使用该数组来构建文件

标签: resourcesiterationpuppet

解决方案


这不太理想,因为我更愿意将它放在定义的资源中,但是因为我使用来自哈希的数据实例化定义的资源,所以我使用所述哈希来迭代该部分。

class xxx_corp_webserver (
  Hash $websites ={}
  ){
  create_resources('xxx_corp_webserver::website', $websites)

  # This would be nicer inside the defined class, but I did not find any other way 
  # Build and array with the IP addresses which are for DSR
  $ipaddresses = $websites.map | $r | {
    if $r[1]['enabledsr'] {
      $r[1]['ipaddress']
      }
    }

  # For each DSR address add the line
  $ipaddresses.each | Integer $index , String $ipaddress | {
    $num = $index+1
    file_line{"dummydsr-ipaddress${num}":
      ensure  => present,
      path    => '/etc/NetworkManager/system-connections/dummydsr',
      line    => "address${num} = ${ipaddress}/32",
      match   => "^address.* = ${ipaddress}/32",
      after   => '# IP Addresses come here',
      notify  => Service['NetworkManager'],
      require => File['/etc/NetworkManager/system-connections/dummydsr'],
      }

    }

}

推荐阅读