2014-04-10 42 views
1

考虑下面的代码片段:木偶 - 应用阵列资源

define custom::line_mgmt ($file, $line) { 
    exec { "/bin/echo '${line}' >> '${file}'" } 
} 

custom::line_mgmt用于插入一个模式,它按预期工作:

$demovar = "TEST1" 
custom::line_mgmt { 
    file => "/tmp/test", 
    line => $demovar, 
} 

但是,如果我想插入来自阵列的多个图案,例如:

$demoarray = [ "TEST1", "TEST2" ] 
custom::line_mgmt { 
    file => "/tmp/test", 
    line => $demoarray, 
} 

它将整个数组视为并尝试在2个不同的迭代中插入TEST1TEST2而不是TEST1,然后TEST2

有人可以指出我的错误吗?

在此先感谢。

回答

0

$line参数假定在字符串表达式"/bin/echo '${line}' >> '${file}'"中使用的数组值。

在Puppet中,数组通过连接它们的所有元素被强制转换为字符串。

木偶(与puppet4之前的解析器,即future_parser=false在Puppet 3.2或更高版本中)只会在数组用于资源标题时“遍历”数组。

custom::line_worker($file) { 
    exec { "/bin/echo '${title}' >> '${file}'" } 
} 
define custom::line_mgmt ($file, $line) { 
    custom::line_worker { $line: file => $file } 
} 

注意,这个崩溃和烧伤,当你想添加类似于线到不同的文件(因为worker资源将具有相同的标题,这是禁止的)。有办法解决这个问题,但这对于这项任务来说可能太麻烦了。

请注意,对于此特定任务,您可以使用puppetlabs-stdlib模块中的file_line类型。

也可以考虑使用templates来完成迭代步骤,甚至可以使用concat模块来管理整个文件。

0

从puppet-3.2可以使用each类型。在这里我给出一个例子,它可以让你将一个字符串数组中的值添加到另一个数组中给出的文件中。你只能指定一个文件,这也应该可以。我正在使用来自puppet stdlib的file_line类型。

class testmodule::test { 

    define linemgmt($file, $line) { 
    file_line { "$file_$line" : 
     path => $file, 
     line => $line, 
    } 
    } 

    $demoarr = [ "test", "test2" ] 
    $demofiles = [ "file1", "file2" ] 

    each($demoarr) | $index, $value | { 
    linemgmt { "test_$index" : 
     file => $demofiles[$index], 
     line => $value, 
    } 
    } 
} 
+0

每个上述工程的解决方案,但是如果未来解析器在puppet.conf启用或作为选项木偶申请通过,这只是,每个是尚未公布木偶4.x的一部分 – Walid