Puppet Tips&Tricks: testing your regsubst replacings

This is part of an ongoing series. Check this for the complete series!

Regular Expressions are important for us. We use them a lot, mostly because it’s such a powerful tool. So our puppet recipes contain several regsubst calls too. One problem is usually that regex can be fairly complex and you’d like a nice way to check it out. After some talk on IRC (#puppet on freenode), monachus gave me some tips for this. Simply use the interactive Ruby shell, irb, for this.

Now, I wanted to check whether a certain string ended in “:ssl” or not. I tested my regex replacement as follows:

$ irb
>> s1="www.kumina.nl:ssl"
=> "www.kumina.nl:ssl"
>> s2="www.kumina.nl"
=> "www.kumina.nl"
>> s1.sub(/.*:(ssl)$/, "\\1")
=> "ssl"
>> s2.sub(/.*:(ssl)$/, "\\1")
=> "www.kumina.nl"

From this I gathered that the resulting regsubst call would be something like this:

if regsubst($name, '.*:(ssl)$', '\1') == "ssl" { ... do stuff ... }

Awesome! Now, if you want to try out a global replace, instead of sub, use gsub.

If you want to use regex in your selector, you can simply use egrep on the commandline, like so:

echo "foo" | egrep "foo|bar"

You can also try it in irb, with the following:

>> a = "foo"
=> "foo"
>> a.match("foo|bar")
=> #<MatchData "foo">
>> b = "beastieboys"
=> "beastieboys"
>> b.match("foo|bar")
=> nil

Hope this helps someone!

Tags: , , , , , , ,

5 Responses to “Puppet Tips&Tricks: testing your regsubst replacings”

  1. Monachus says:

    Hey – thanks for the shoutout! If you can change “monarchus” to “monachus” that would be awesome.

  2. Tim Stoop says:

    Woops… 🙂

  3. Walter Heck says:

    The regsubst link in this article is outdated 😉

  4. Tim Stoop says:

    Fixed! Thanks for letting us know.

  5. Vicente says:

    Thank you very much. This was really helpfull for me.

Leave a Reply

Kumina designs, builds, operates and supports Kubernetes solutions that help companies thrive online. As Certified Kubernetes Service Partner, we know how to build real solutions.