Search code examples
stringvariablesscopepuppet

Puppet conditional assignment and += operator


In puppet, I want to write a file with a string based on configuration in nodes.pp.

  • nodes.pp defines the $sslClientCertConfig variable, which has a loadBalancerIp property.
  • I want to create a configuration string, we'll call it $config, without repeating the string code. The configuration string should be either
    • A: if loadBalancerIp is a valid string, a combination of strings 1 and 2
    • B: if loadBalancerIp is an empty string, only string 2
  • Then, using that configuration string, I want to set another variable.

I know that puppet only allows a single declaration of a variable name per scope, but I do not know if it supports the += operator, or if the variable declarations below will work for the if/else clause later.

Here's what I want to try:

if $sslClientCertConfig {
    $loadBalancerIp = $sslClientCertConfig[loadBalancerIp]

    $config

    if $loadBalancerIp {
          $config += "string1"
    }
    $config += "string2"
}

if $config {
   $custom = "true"
} else {
    $custom = "false"
}

Is this pattern supported by puppet? Is there a way I can improve this?


Solution

  • You cannot reassign variables in puppet. Instead remove empty declaration of $config and try the following code

    if $loadBalancerIp {
          $prefix = "string1"
    }
    $config = "${prefix}string2"
    

    Example:

    $prefix1 = "pref1"
    $config1 = "${prefix1}blabla1"
    $config2 = "${prefix2}blabla2"
    notify { $config1: }
    notify { $config2: }
    

    Notice: /Stage[main]/Main/Notify[pref1blabla1]/message: defined 'message' as 'pref1blabla1' Notice: /Stage[main]/Main/Notify[blabla2]/message: defined 'message' as 'blabla2'

    UPDATE: Be aware of automatic string to boolean conversion.