Puppet template erb if variable is not defined keep default

mYzk asked:

I am trying to learn puppet and I can not understand how I can setup template erb to choose default value if variable is not defined in common.yaml or in node.yaml. This is what I have tried:
1)

# we don't need to run the embedded HTTP server here
<% if @elasticsearch_http_enabled %>
elasticsearch_http_enabled = <%= @elasticsearch_http_enabled %>
<% else %>
#elasticsearch_http_enabled = false
<% end %>

2)

# we don't need to run the embedded HTTP server here
<%- if @elasticsearch_http_enabled then -%>
elasticsearch_http_enabled = <%= @elasticsearch_http_enabled %>
<% else %>
#elasticsearch_http_enabled = false
<% end %>

3)

# we don't need to run the embedded HTTP server here
<% if @elasticsearch_http_enabled then %>
elasticsearch_http_enabled = <%= @elasticsearch_http_enabled %>
<% else %>
#elasticsearch_http_enabled = false
<% end %>

When I tried these I got error:

Error: Could not retrieve catalog from remote server: Error 400 on
SERVER: Could not find data item gl2_srv_elasticsearch_http_enabled in
any Hiera data file and no default supplied at
/etc/puppet/envs/testing/modules/graylog2/manifests/server.pp:28 on
node

How can I make it so if I do not define the variable it puts the default variable to the config.

My answer:


None of the above.

Instead, supply defaults for all of your parameters in, e.g. a manifests/params.pp.

An example init.pp:

class elasticsearch (
    $http_enabled        = $::elasticsearch:params:http_enabled,
) inherits ::elasticsearch:params {
    # your class here
}

An example params.pp:

class elasticsearch:params {
    $http_enabled = false 
}

This lets you isolate code which must choose different defaults for, e.g. different operating systems or distributions.

If you’re 100% sure the default should always be false, you can just declare it as such in init.pp and forget about adding it to params.pp.

class elasticsearch (
    $http_enabled        = false,
) inherits ::elasticsearch:params {
    # your class here
}

Your template is then simplified to:

elasticsearch_http_enabled = <%= @http_enabled %>

View the full question and answer on Server Fault.

Creative Commons License
This work is licensed under a Creative Commons Attribution-ShareAlike 3.0 Unported License.