Puppet templates and undefined/nil variables
5,397
Couldn't you just set a default in the class definition?
class myclass ($a_variable = "a default value") {
Related videos on Youtube
Author by
user2751502
Updated on September 18, 2022Comments
-
user2751502 over 1 year
I often want to include default values in Puppet templates. I was hoping that given a class like this:
class myclass ($a_variable=undef) { file { '/tmp/myfile': content => template('myclass/myfile.erb'), } }
I could make a template like this:
a_variable = <%= a_variable || "a default value" %>
Unfortunately,
undef
in Puppet doesn't translate to a Rubynil
value in the context of the template, so this doesn't actually work. What is the canonical way of handling default values in Puppet templates?I can set the default value to an empty string and then use the
empty?
test...a variable = <%= a_variable.empty? ? "a default value" : a_variable %>
...but that seems a little clunky.
-
daff about 12 yearsThat "PSA" sounds more like someone frustrated with Puppet needing to vent. Nothing in the Puppet documentation suggests that a construct like "my_var ||= 'some default value'" would or should be valid Puppet manifest code, but that doesn't stop him from complaining.
-
user2751502 about 12 yearsWell, the fact that Puppet templates use ERB sure suggests that basic variable interpolation is going to work in templates as it does in Ruby. Furthermore, things like hash lookups behave identical to standard Ruby code (e.g., you can do
somehash['key-that-does-not-exist'] || "a value"
and it works just fine). So yes, he sounds a bit frustrated, but he's not completely off base. The syntax is inconsistent and there's not a lot of documentation on how Puppet's variable behave different from Ruby variables. -
daff about 12 yearsApologies, I misread the blog post slightly. I thought he was talking about using
my_var ||= 'some default value
in a manifest (i.e. foo.pp), but instead he is talking about templates and ERB. There is certainly a point to be made about the various inconsistent and non-intuitive ways variables are handled in templates. The wholescope.lookupvar()
business since 2.7.0, for example. But I think in that way Puppet is still evolving, and I don't think Chef has found the answers to all that, like the blog post seems to be implying.
-
-
daff about 12 yearsThis is the way to go in my experience.
-
user2751502 about 12 yearsI already do that...but my question was about moving it into the template file, mostly as a matter of clarity for someone looking at the template.
-
AWippler almost 11 yearsWhy not add a comment in the template file? <%# comment goes here %>