aboutsummaryrefslogtreecommitdiff
path: root/manifests/defines/replace.pp
blob: a7a59b8b26bd332a102f587c6582d29d6973b5cf (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
# 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.

# 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.
# 
# Usage:
#
# replace { description: 
#           file => "filename",
#           pattern => "regexp",
#           replacement => "replacement"
#
# Example:
# To replace the current port in /etc/munin/munin-node.conf
# with a new port, but only disturbing the file when needed:
#
# replace { set_munin_node_port:
# 	file => "/etc/munin/munin-node.conf",
# 	pattern => "^port (?!$port)[0-9]*",
# 	replacement => "port $port"
# }  

define replace($file, $pattern, $replacement) {
	$pattern_no_slashes = regsubst($pattern, '/', '\\/', 'G', 'U')
	$replacement_no_slashes = regsubst($replacement, '/', '\\/', 'G', 'U')

	exec { "replace_${pattern}_${file}":
		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}'",
		alias => "exec_$name",
	}
}