Puppet variables set in exec environment not accessible elsewhere in the class

environment-variablesexecpuppet

I'm trying to configure a logging figuration with log paths based on a check to see if that log file exists. However, the if statements always return true even though I know /var/log/hermes/hermes.log doesn't exist. I have tested the exec {"service_log_check" onlyif is working so it's something to do with the if statement. I had thought about adding within each exec something like environment => ["FOO=true" and then changing the if statement to if $FOO == true but it appears that variables set within exec environment are only accessible within the exec not the whole class. It's driving me crazy!!! We are using puppet v3.7

class hermes::fluentd($service_name='hermes', $logs='/var/log/test/test.log') {

exec {"service_log_check":
  command => '/bin/true',
  onlyif => '/usr/bin/test -e /var/log/hermes/hermes.log',
}

exec {"service_log_json_check":
  command => '/bin/true',
  onlyif => '/usr/bin/test -e /var/log/hermes/hermes-json.log',
}

exec {"request_log_check":
  command => '/bin/true',
  onlyif => '/usr/bin/test -e /var/log/hermes/request.log',
}

if service_log_check {
    $service_logs = "/var/log/${service_name}/${service_name}.log"
}
else { $service_logs = []
}

if service_log_json_check {
    $service_json_logs = "/var/log/${service_name}/${service_name}-json.log"
}
else { $service_json_logs = []
}

if request_log_check {
    $service_request_logs = "/var/log/${service_name}/request.log"
}
else
{ $service_request_logs = []
}

$logs_to_tail = [$logs, $service_logs, $service_json_logs, $service_request_logs]


file { "/etc/td-agent/config.d/${service_name}_service_logs.conf":
    ensure => present,
    content => template('service_logs.conf.erb'),
    owner  => td-agent,
    group  => td-agent,
    mode   => '0775'
}

}

Best Answer

Unfortunately that's not how puppet works. Exec resources cannot set values that can be referred to by other code in the puppet manifest. There's a few concepts here that you need to understand:

  1. Puppet is 'declarative', not a 'script'. You are declaring the Desired State, and puppet takes care of getting the target machine into that state.
  2. The manifest (declaration of desired state) is compiled before it is applied; variables are only evaluated at that point, long before the exec is executed

If you need to get information from the node to make decisions about what your desired state is (i.e. what values to put in the .conf file), you need to write a Custom Fact (see https://docs.puppet.com/facter/3.7/custom_facts.html)