2007-09-11 10:29:38 +02:00
|
|
|
# common/manifests/defines/replace.pp -- replace a pattern in a file with a string
|
|
|
|
# Copyright (C) 2007 David Schmitt <david@schmitt.edv-bus.at>
|
|
|
|
# See LICENSE for the full license granted to you.
|
|
|
|
|
2009-05-31 21:14:37 +02:00
|
|
|
# A hack to replace all ocurrances of a regular expression in a file with a
|
|
|
|
# specified string. Sometimes it can be less effort to replace only a single
|
|
|
|
# value in a huge config file instead of creating a template out of it. Still,
|
|
|
|
# creating a template is often better than this hack.
|
|
|
|
#
|
|
|
|
# This define uses perl regular expressions.
|
2009-06-09 17:51:10 +02:00
|
|
|
#
|
|
|
|
# Use this only for very trivial stuff. Usually replacing the whole file is a
|
|
|
|
# more stable solution with less maintenance headaches afterwards.
|
2009-05-31 21:14:37 +02:00
|
|
|
#
|
2007-09-11 10:29:38 +02:00
|
|
|
# Usage:
|
|
|
|
#
|
2007-10-05 22:04:31 +02:00
|
|
|
# replace { description:
|
|
|
|
# file => "filename",
|
|
|
|
# pattern => "regexp",
|
|
|
|
# replacement => "replacement"
|
|
|
|
#
|
2007-10-05 22:04:32 +02:00
|
|
|
# Example:
|
|
|
|
# To replace the current port in /etc/munin/munin-node.conf
|
2007-10-05 22:04:31 +02:00
|
|
|
# with a new port, but only disturbing the file when needed:
|
|
|
|
#
|
2009-06-09 17:51:10 +02:00
|
|
|
# replace {
|
|
|
|
# set_munin_node_port:
|
|
|
|
# file => "/etc/munin/munin-node.conf",
|
|
|
|
# pattern => "^port (?!$port)[0-9]*",
|
|
|
|
# replacement => "port $port"
|
|
|
|
# }
|
2007-09-11 10:29:38 +02:00
|
|
|
define replace($file, $pattern, $replacement) {
|
2009-05-31 21:14:37 +02:00
|
|
|
$pattern_no_slashes = regsubst($pattern, '/', '\\/', 'G', 'U')
|
|
|
|
$replacement_no_slashes = regsubst($replacement, '/', '\\/', 'G', 'U')
|
|
|
|
|
2007-09-11 10:29:38 +02:00
|
|
|
exec { "replace_${pattern}_${file}":
|
2007-11-13 10:44:07 +01:00
|
|
|
command => "/usr/bin/perl -pi -e 's/${pattern_no_slashes}/${replacement_no_slashes}/' '${file}'",
|
|
|
|
onlyif => "/usr/bin/perl -ne 'BEGIN { \$ret = 1; } \$ret = 0 if /${pattern_no_slashes}/ && ! /\\Q${replacement_no_slashes}\\E/; END { exit \$ret; }' '${file}'",
|
2007-09-11 10:29:38 +02:00
|
|
|
alias => "exec_$name",
|
|
|
|
}
|
|
|
|
}
|