Search code examples
regexpuppet

how to test with parameterized regex (e.g. /${user}/) on puppet?


I need to get a user's home directory. I decided to get it with parsing a ::getent_passwd string (which is a custom fact build as concatenation of the contents of the /etc/passwd) and extract the relevant information with the help of the regex.

When I test the ::getent with fixed string ("adam"), extraction works:

if "$::getent_passwd" =~ /\|adam:x:[^:]+:[^:]+:[^:]*:([^:]*):/ {
  $user_home = $1
  notify{"This works":}
}

But when I build a regex with the $user variable, nothing gets matched:

if "$::getent_passwd" =~ /\|${user}:x:[^:]+:[^:]+:[^:]*:([^:]*):/ {
  $user_home = $1
} else {
  fail{"this fails":}
}

Client and server use Puppet 3.7.3 on Ubuntu 14.04 64bit. Puppetserver uses puppetdb.


Solution

  • An answer five years later, but now there's an easy way. For others landing here... Try the regexp constructor to build a regexp from a string :

    if("abcd" =~ Regexp("${myvar}") { (...) }