请考虑以下代码段:
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 :(得分:0)
$line
参数假定字符串表达式"/bin/echo '${line}' >> '${file}'"
中使用的数组值。
在Puppet中,通过连接所有元素将数组强制转换为字符串。
Puppet(使用pre-puppet4解析器,即Puppet future_parser=false
或更高版本中的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
类型。
答案 1 :(得分: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,
}
}
}