puppethiera

How to add an if statement inside a Puppet class creation


I have a Puppet manifest which creates a class, with another class inside it:

class profiles::common::wlsdomains {
    class {"wlsdomain":
            applications      => hiera('wlsapplications', ""),
            crontab           => hiera_hash('crontab', ""),
            generateWlsdomain => hiera('generatewlsdomain'), # This line needs changing
    }
}

So far so good. Now, the problem is the last line. I only want to set "generateWlsdomain" to "hiera('generatewlsdomain')" under certain conditions. This is where the need for an "if" statement comes in. I'd like to replace that line with something like this:

if $::generate == "true" {
    generatewlsdomain => "true"
}
elsif $::generate == "false" {
    # Do nothing; leave generatewlsdomain unset
}
else { # If $::generate is neither "true" nor "false", then get a value from Hiera
    generateWlsdomain => hiera('generatewlsdomain'),
}

In other words, I want to primarily look at $::generate to decide what to do, but use a value from Hiera as backup if $::generate isn't set.

However, something tells me I can't just replace the existing line with this code block, because the existing line is part of a comma-separated list, it's not just a generic code line of its own.

In case it matters, this is running on a RedHat machine.


Solution

  • The undef keyword can be used as the value if you don't want to set it, which will cause Puppet to use the default value for generateWlsdomain.

    Using this, set a variable for the value of generateWlsdomain:

    if $::generate == "true" {
        $generatewlsdomain = "true"
    }
    elsif $::generate == "false" {
        $generatewlsdomain = undef # Do nothing; leave generatewlsdomain unset
    }
    else { # If $::generate is neither "true" nor "false", then get a value from Hiera
        $generatewlsdomain = hiera('generatewlsdomain')
    }
    

    or a bit more compact, using a selector to test $::generate values and set $generatewlsdomain with the result:

    $generatewlsdomain = $::generate ? {
      "true"  => "true",
      "false" => undef, # Do nothing; leave generatewlsdomain unset
      default => hiera('generatewlsdomain'), # If neither "true" nor "false", then get a value from Hiera
    }
    

    and pass it into the existing class declaration:

    class {"wlsdomain":
      applications      => hiera('wlsapplications', ""),
      crontab           => hiera_hash('crontab', ""),
      generateWlsdomain => $generatewlsdomain,
    }