25

Is it possible to do a string substitution/transformation in Puppet using a regular expression?

If $hostname is "web1", I want $hostname_without_number to be "web". The following isn't valid Puppet syntax, but I think I need something like this:

$hostname_without_number = $hostname.gsub(/\d+$/, '')
richardkmiller
  • 2,902
  • 3
  • 31
  • 29

2 Answers2

42

Yes, it is possible.

Check the puppet function reference: http://docs.puppetlabs.com/references/2.7.3/function.html

There's a regular expression substitution function built in. It probably calls the same underlying gsub function.

$hostname_without_number = regsubst($hostname, '\d+$', '')

Or if you prefer to actually call out to Ruby, you can use an inline ERB template:

$hostname_without_number = inline_template('<%= hostname.gsub(/\d+$/, "") %>')
freiheit
  • 4,976
  • 37
  • 35
  • 1
    Thanks! I'll use the built-in regsubst() this time, but I'm very glad to know about inline_template as well! That's very flexible. – richardkmiller May 05 '12 at 17:12
  • 1
    It's worth pointing out that `regsubst()` also supports a flags arg in the 4th position. A flag such as 'G' will globally replace all matches in the provided string. – killthrush Aug 18 '16 at 14:15
  • Providing Puppet v6 version of the link https://puppet.com/docs/puppet/6/function.html – Ceddaerrix Oct 22 '21 at 06:35
2

In this page:

https://blog.kumina.nl/2010/03/puppet-tipstricks-testing-your-regsubst-replacings-2/comment-page-1/

it is quite well explained and there is a fantastic trick for testing your regular expressions with irb.

Whith this link and the answer of freiheit I could resolve my problem with substitution of '\' for '/'.

$programfiles_sinbackslash = regsubst($env_programfiles,'\','/','G')

IAmAliYousefi
  • 1,132
  • 3
  • 21
  • 33
user45949
  • 2,524
  • 1
  • 13
  • 3